
/*****************静态数据******************/
var taskListModel=[{
	id:1,
	description:'联想官方直营4S店（金源新燕莎MALL）一周岁生日啦！',
	photo_url:'/images/temp/1.jpg',
	timestamp:1466995184280,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar1.png'
	}
},{
	id:2,
	description:'第三次水果摊战役',
	photo_url:'http://cdn2.parllay.cn/2016090616/gw829o1ckpkcw.mp4',  //'http://cdn2.parllay.cn/2016090815/be3cln86wtcko.mp4',
	poster:'/images/temp/2.jpg',
	ratio:0.75,
	isVideo:true,
	timestamp:1466995184279,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:true,
	likes:1,
	user:{
		id:'1',
		name:'菜市场浪人',
		profile_image:'/images/avatar2.png'
	}
},{
	id:3,
	description:'花鸟鱼虫市场的陷落',
	photo_url:'/images/temp/4.jpg',
	timestamp:1466995184278,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'兽王',
		profile_image:'/images/avatar4.png'
	}
},{
	id:4,
	description:'西十楼守城战',
	photo_url:'http://cdn2.parllay.cn/2016090815/be3cln86wtcko.mp4',  //'/images/temp/3.jpg',
	poster:'/images/temp/3.jpg',
	ratio:0.74,
	isVideo:true,
	timestamp:1466995184277,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'游侠',
		profile_image:'/images/avatar3.png'
	}
},{
	id:5,
	description:'联想官方直营4S店（金源新燕莎MALL）一周岁生日啦！',
	photo_url:'/images/temp/5.jpg',
	timestamp:1466995184276,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar5.png'
	}
},{
	id:6,
	description:'天地批发市场正式宣布与菜市场结盟',
	photo_url:'/images/temp/6.jpg',
	timestamp:1466995184275,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar1.png'
	}
},{
	id:7,
	description:'广场舞修道会宣誓效忠居委会',
	photo_url:'/images/temp/7.jpg',
	timestamp:1466995184274,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar2.png'
	}
},{
	id:8,
	description:'玉泉路合战战术分析（终极版）',
	photo_url:'/images/temp/8.jpg',
	timestamp:1466995184273,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar3.png'
	}
},{
	id:9,
	description:'居委会大使孟主任前往太平路中学进行结盟游说但收效甚微',
	photo_url:'/images/temp/9.jpg',
	timestamp:1466995184272,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar4.png'
	}
},{
	id:10,
	description:'菜市场使者老赵宣称若太平路中学加入居委会一方将不再对其手下留情',
	photo_url:'/images/temp/10.jpg',
	timestamp:1466995184271,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar5.png'
	},
	source:'PC'
}/*,

{
	id:11,
	description:'联想官方直营4S店（金源新燕莎MALL）一周岁生日啦！',
	photo_url:'/images/temp/1.jpg',
	timestamp:1466995184270,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar1.png'
	}
},{
	id:12,
	description:'第三次水果摊战役',
	photo_url:'/images/temp/2.jpg',
	timestamp:1466995184269,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'菜市场浪人',
		profile_image:'/images/avatar2.png'
	}
},{
	id:13,
	description:'西十楼守城战',
	photo_url:'/images/temp/3.jpg',
	timestamp:1466995184268,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'游侠',
		profile_image:'/images/avatar3.png'
	}
},{
	id:14,
	description:'花鸟鱼虫市场的陷落',
	photo_url:'/images/temp/4.jpg',
	timestamp:1466995184267,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'兽王',
		profile_image:'/images/avatar4.png'
	}
},{
	id:15,
	description:'联想官方直营4S店（金源新燕莎MALL）一周岁生日啦！',
	photo_url:'/images/temp/5.jpg',
	timestamp:1466995184266,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar5.png'
	}
},{
	id:16,
	description:'天地批发市场正式宣布与菜市场结盟',
	photo_url:'/images/temp/6.jpg',
	timestamp:1466995184265,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar1.png'
	}
},{
	id:17,
	description:'广场舞修道会宣誓效忠居委会',
	photo_url:'/images/temp/7.jpg',
	timestamp:1466995184264,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar2.png'
	}
},{
	id:18,
	description:'玉泉路合战战术分析（终极版）',
	photo_url:'/images/temp/8.jpg',
	timestamp:1466995184263,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar3.png'
	}
},{
	id:19,
	description:'居委会大使孟主任前往太平路中学进行结盟游说但收效甚微',
	photo_url:'/images/temp/9.jpg',
	timestamp:1466995184262,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar4.png'
	}
},{
	id:20,
	description:'菜市场使者老赵宣称若太平路中学加入居委会一方将不再对其手下留情',
	photo_url:'/images/temp/10.jpg',
	timestamp:1466995184261,
	sourceLogo:'/images/icons/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar5.png'
	}
},
{
	"id":21,
	"user":{
		"id":"5775d9ff4e0cec66550e60bb",
		"profile_image":"http://wx.qlogo.cn/mmopen/nv5AAf1bGG2zNs2miaPN6069AyBxJ77a0csKhuwicszrGru9WXJXnxRtFu49FC3RtDTicKLM9LibtA53WyicLPjmjfVfFuJRBCFLL/0",
		"name":"Tarek Najm"
	},
	"photo_url":"//cdn2.parllay.cn/2016071912/8kgfrhvrxjc4g.jpeg",
	"description":"Healthy dinne for all!",
	"ratio":1.33,
	"is_liked":false,
	"likes":1,
	"status":"approved",
	"timestamp":1468903748120
}*/];

/*****************backbone 模型******************/

var CollectionList = Backbone.Collection.extend({
	model:function(attrs){
		if(attrs.source=='PC'){
			if(attrs.type=='video'){
				attrs.isVideo=true;
				attrs.poster=attrs.asset_meta_data.poster_image;
			}
			attrs.ratio=attrs.asset_meta_data && !attrs.ratio?attrs.asset_meta_data.ratio:attrs.ratio
		}
		if(!($(window).width()<768 && !isTV()) && attrs.type!='video'){
			attrs.photo_url=attrs.photo_url+(attrs.photo_url.indexOf('imageMogr/auto-orient')>=0?'':'?imageMogr/auto-orient')
		}
		return new Backbone.Model(attrs)
	}
});

/*****************react mixins******************/
/*多图瀑布流继承此类*/
var WaterFaller=function(){
	return {
		//new function
		minWidth:250,
		minHeight:250,
		serial:false,
		lastLimitSizeWidth:1,
		getContentWidth:function(){
			var content=this.refs.main || this.refs.giant_screen;

			return $(content).width()
		},
		getContentHeight:function(){
			var content=this.refs.main || this.refs.giant_screen;

			return $(content).height()
		},
		getColNum:function(){
			var contentWidth=this.getContentWidth(),
				minWidth=this.minWidth;

			return !this.props.isPhone?Math.ceil(contentWidth/minWidth):1
		},
		getRowNum:function(){
			var contentHeight=this.getContentHeight(),
				minHeight=this.minHeight;

			return Math.ceil(contentHeight/minHeight)
		},
		getMaximumCol:function(){
			var colNum=this.getColNum();

			return colNum<4?1:2 //colNum>=4 && colNum<7?2:3
		},
		getMaximumRow:function(){
			var rowNum=this.getRowNum();

			return rowNum-1
		},
		getAverageWidth:function(list){
			var totalFirstPage=0,
				totalNextPage=0,
				len=this.len || list.length;

			list.forEach(function(i,index){
				if(index<len){
					totalFirstPage+=i.width || 0
				}else{
					totalNextPage+=i.width || 0
				}
			});

			return [parseInt(totalFirstPage/len),parseInt(totalNextPage/(list.length-len))];
		},
		getAverageHeight:function(){
			var listArray=(this.state?this.state.listArray:null) || this.props.collection.toJSON(),
				total=0;

			listArray.forEach(function(i){
				total+=i.height || 0
			});

			return parseInt(total/listArray.length);
		},
		
		getItemFinalSize:function(real,avg,max){
			/*var colNum=this.getColNum(),
				realCol=Math.ceil(real/this.minWidth),
				col=Math.min(Math.round((realCol/colNum)*(max-1)+1),max);
			console.log(col)
			return col*/
			return Math.min(Math.ceil(real/(avg*2/max)),max)
		},
		getLimitSizeArr:function(list){
			var self=this,
				avgWidth=this.getAverageWidth(list),
				maxItemCol=this.getMaximumCol(),
				len=this.len || list.length;
			 
			return list.map(function(model,index){
				if(model.ratio){
					var itemCol=self.getItemFinalSize(model.width,avgWidth[(index<len?0:1)],maxItemCol) || 1,
						itemRow=Math.round(model.ratio*itemCol) || 1;

					return {
						col:itemCol,
						row:itemRow,
						index:index
					}
				}
			})
		},
		getLayout:function(){
			var self=this,
				layout=[],
				isAuditing=this.props.isAuditing,
				wallMode=isAuditing?0:this.props.wallMode,
				listArray=(this.state?this.state.listArray:null) || this.props.collection.toJSON(),
				colNum=this.getColNum(),
				tempArr=_.clone(this.placeholder),
				minWidth=this.minWidth,
				minHeight=this.minHeight,
				limitSizeArr=wallMode==4?this.getLimitSizeArr(listArray):null,
				maxItemCol=wallMode==4?this.getMaximumCol():null;
			
			listArray.forEach(function(model,index){
				var position={},
					col=Math.min(tempArr.length!=colNum?tempArr.length:_.indexOf(tempArr,_.min(tempArr)),colNum-1),
					t=tempArr[col] || 0;
				
				if(colNum>1){
					switch(wallMode){
						case 0:
							if(model.h){
								if(wallMode==0){
									position={
										w:minWidth,
										h:model.h,
										l:col*minWidth,
										t:t
									}
									tempArr[col]=t+model.h
								}
							}
							break;
						case 1:
						case 4:
							if(model.ratio){
								if(wallMode==1){
									position={
										w:minWidth,
										h:model.ratio*minWidth,
										l:col*minWidth,
										t:t
									}
									tempArr[col]=t+model.ratio*minWidth
								}else{
									if(index==self.len){
										self.serial=true
									}

									var serial=self.serial,
										expectWidth=serial?(self.lastLimitSizeWidth-1 || 1):Math.min(colNum-col,maxItemCol),
										gap=(function(g){
											for(var i=1;i<g;i++){
												if((tempArr[col+i] || 0) != t){
													return i
												}
											}
											return g
										})(expectWidth),
										item=null,
										Num=0,
										w=0,
										h=0,
										isFirstPage=index<self.len,
										searchTheArr=function(num){
											if(num<maxItemCol-1){
												limitSizeArr=_.reject(limitSizeArr,function(i){
													var index2=i.index;
													if((isFirstPage?(index2<self.len):(index2>=self.len))){
														if(!item && (i.col==gap-num)){
															//console.log(index2)
															item=i;
															self.serial=i.col>1;
															return true
														}
													}
													
													return false
												})
											}else{
												item=limitSizeArr.splice(0,1)[0];
												self.serial=item.col>1
											}
										};
									
									while(!item){
										searchTheArr(Num++)
									}

									if(item.col <= gap){
										w=item.col;
										h=item.row
									}else{
										w=gap;
										h=Math.round(model.ratio*gap)
									}

									self.lastLimitSizeWidth=w;

									position={
										w:w*minWidth-10,
										h:h*minHeight-10,
										l:col*minWidth+5,
										t:t+5,
										index:item.index
									}
									
									for(var j=0;j<w;j++){
										tempArr[col+j]=(tempArr[col+j] || 0)+h*minHeight
									}
									//console.log(colNum)
								}
							}
							break;
						case 2:
						case 3:
							position={
								l:index%colNum*minWidth+10,
								t:parseInt(index/colNum)*minWidth+10
							};
							break;

					}
				}

				if(position.index>=0){
					layout[position.index]=position
				}else{
					layout.push(position)
				}

			});

			if(colNum>1 && (wallMode==2 || wallMode==3)){
				tempArr=[Math.ceil(listArray.length/colNum)*minWidth]
			}

			this.serial=true;

			this.tempArr=tempArr;

			return layout
		},
		//old function
		placeholder:[],
		placeholderTemp:[],
		len:0,
		/*shouldComponentUpdate:function(nextProps, nextState){
			var state=this.state;
			return (state.mainTop!=nextState.mainTop)  //(state.listArray.length!=nextState.listArray.length) || (state.mainTop!=nextState.mainTop)
		},
		componentDidMount:function(){
			this.animationStart()
		},*/
		animationStart:function(){
			var self=this,
				windowHeight=$(window).height(),
				listArray=this.state.listArray,
				tempArr=_.clone(this.tempArr),
				max=_.max(tempArr)+100,
				//min=_.min(tempArr)-100,
				//screenSize=Math.ceil(windowHeight/min),
				collection=this.props.collection.toJSON(),
				wallSpeed=this.props.wallSpeedList[this.props.wallSpeed].val,
				duration=max/wallSpeed*50,
				state={};

			this.len=_.clone(listArray).length;
			listArray=listArray.concat(collection);
			/*if(screenSize>1){
				for(var i=1;i<screenSize;i++){
					listArray=listArray.concat(collection)
				}
			}*/

			state.listArray=listArray;

			this.placeholderTemp=tempArr;

			this.setAnimationStyle(duration/1000,function(){
				self.scrollTo(-max,function(){
					self.timer=setTimeout(function(){
						self.animationNext()
					},duration)
				})
			},state)
		},
		animationNext:function(){
			var self=this,
				listArray=this.state.listArray,
				placeholderTemp=_.clone(this.placeholderTemp),
				max=_.max(placeholderTemp)+100,
				state={};

			this.placeholder=_.map(placeholderTemp,function(i){
				return i-max
			});

			listArray.splice(0,this.len);

			this.len=_.clone(listArray).length;

			state.listArray=listArray;

			this.setAnimationStyle(0,function(){
				self.scrollTo(0,function(){
					self.animationStart()
				})
			},state)
		},
		getNewPage:function(height){
			var collection=this.props.collection,
				collectionArr=collection.toJSON(),
				len=collection.length,
				lastItemId=this.lastItemId,
				lastItemIndex=lastItemId?_.findIndex(collectionArr,function(i){ return i.id==lastItemId}):0,
				result=[];

			while(number>0){
				var targetIndex=_.min([lastItemIndex+number,len]);
				result=result.concat(collectionArr.slice(lastItemIndex,targetIndex));
				number=number-(targetIndex-lastItemIndex);
				lastItemIndex=targetIndex==len?0:targetIndex
			}
			this.lastItemId=collection.at(lastItemIndex).get('id');

			return result
		},
		scrollTo:function(distance,callback){
			this.setState({
				mainTop:distance
			},callback)
		},
		setAnimationStyle:function(duration,callback,state){
			state.tranStyle=duration?{
				'transition':'all '+duration+'s linear',
			    'OTransition':'all '+duration+'s linear',
			    'MsTransition':'all '+duration+'s linear',
			    'MozTransition':'all '+duration+'s linear',
			    'WebkitTransition':'all '+duration+'s linear'
			}:{};

			this.setState(state,callback)
		}
	}
};

/*多图卡片继承此类*/
var ListItemMixin=function(){
	return {
		refresh:function(){
			var model=_.clone(this.props.model);

			this.timer=setTimeout(function(){
				if(ReactDOM.findDOMNode()){
					this.setState({
						time:moment(new Date(_.min([model.timestamp,Date.now()-45000]))).fromNow()
					});
					this.refresh()
				}
			}.bind(this),60000);
		},
		componentWillUnmount:function(){
			clearTimeout(this.timer)
		},
		like:function(){
			var self=this,
				model=this.props.model,
				id=model.id,
				isLiking=this.state.isLiking,
				is_liked=this.state.is_liked,
				url;
			
			if(!isLiking){
				this.setState({
					isLiking:true
				});

				if(!is_liked){
					url='/walls/'+wallId+'/photos/'+id+'/like'
				}else{
					url='/walls/'+wallId+'/photos/'+id+'/unlike'
				}

				$.ajax({
					type:'post',
					url:url,
					dataType:'json',
					success:function(data){
						if(data.success){
							self.setState({
								likes:data.data,
								is_liked:!is_liked,
								isLiking:false,
								showLikeAnimation:true
							})
						}
					}
				})
			}
		},
		handle:function(method){
			var app=this.props.app,
				model=this.props.model,
				id=model.id,
				status=this.props.status=='approved'?'main':this.props.status;

			$.ajax({
				type:'post',
				url:'/walls/'+wallId+'/photos/'+id+'/'+method,
				dataType:'json',
				success:function(data){
					console.log(data);
					console.log(id);
					if(data.success && data.data){
						switch(method){
							case 'approve':
								var m=app.removeModel(status+'Collection',id);
								if(m){
									m.set('timestamp',app.getNewTimestamp('mainCollection',m));
									app.addMedel('mainCollection',m)
								}
								break;
							case 'reject':
								var m=app.removeModel(status+'Collection',id);
								if(m){
									m.set('timestamp',app.getNewTimestamp('rejectedCollection',m));
									app.addMedel('rejectedCollection',m)
								}
								break;
							case 'delete':
								var m=app.removeModel(status+'Collection',id);
								if(m){
									m.set('timestamp',app.getNewTimestamp('deletedCollection',m));
									app.addMedel('deletedCollection',m)
								}
								break;
						}
						
					}
				}
			})
		}
	}
};

/*****************react 模块******************/
/*图片墙*/
var MainList = React.createClass({
	mixins:[WaterFaller()],
	componentWillMount:function(){
		var self=this,
			app=this.props.app,
			timer=null;
		$(window).unbind('resize').bind('resize',function(){
			if(timer){clearTimeout(timer)}

			timer=setTimeout(function(){
				var isPhone=$(window).width()<768;

				app.react.setState({
					isPhone:isPhone
				},function(){
					self.forceUpdate();
					console.log('resize');
					timer=null
				})
				self.isloaded=false
			},500)
		})
	},
	componentWillUnmount:function(){
		$(window).unbind('resize')
	},
	render:function(){
		var app=this.props.app,
			isAuditing=this.props.isAuditing,
			message=this.props.message,
			wallMode=isAuditing?0:this.props.wallMode,
			wallBackground=this.props.wallBackground,
			wallColor=this.props.wallColor,
			collection=this.props.collection,
			len=collection.length,
			isPhone=this.props.isPhone,
			listHtml=[],
			layout=this.getLayout(),
			className='main',
			status=this.props.status || 'pending';

			className+=wallMode==4?' main-sizelimit':'';

			collection.forEach(function(i,index){
				var model=i.toJSON();

				switch (wallMode){
					case 0:
						listHtml.push(<MainListItem key={index} isPhone={isPhone} position={layout[index]} app={app} model={model} backboneModel={i} index={index} wallColor={wallColor} isAuditing={isAuditing} status={status} />);
						break;
					case 1:
					case 4:
						listHtml.push(<MainListPicItem key={index} isPhone={isPhone} position={layout[index]} model={model} backboneModel={i} index={index} wallColor={wallColor} />);
						break;
					case 2:
					case 3:
						listHtml.push(<MainListGemItem key={index} isPhone={isPhone} position={layout[index]} model={model} index={index} wallColor={wallColor} wallMode={wallMode} />);
						break;
				}
			});		

		return (
			<div className={className} style={{backgroundColor:wallBackground}}>
				{isAuditing?<ul className="nav nav-tabs pull-left navStyle navStyle-admin">
					<li className={"navStyleLi "+(status=='pending'?'navStyleLi-active':'')}><a className="liAStyle" href="#auditing/pending"><i className="glyphicon glyphicon-time"></i><b>待处理</b></a></li>
					<li className={"navStyleLi "+(status=='approved'?'navStyleLi-active':'')}><a className="liAStyle" href="#auditing/approved"><i className="glyphicon glyphicon-ok"></i> <b>批准</b></a></li>
					<li className={"navStyleLi "+(status=='rejected'?'navStyleLi-active':'')}><a className="liAStyle" href="#auditing/rejected"><i className="glyphicon glyphicon-remove"> </i><b>拒绝</b></a></li>
					<li className={"navStyleLi "+(status=='deleted'?'navStyleLi-active':'')}><a className="liAStyle" href="#auditing/deleted"><i className="glyphicon glyphicon-trash"></i> <b>删除</b></a></li>
				</ul>:''}
				<div id="main" ref="main" style={{height:_.max(this.tempArr) || 'auto',marginTop:isAuditing?'38px':null}}>
					{<center className="hd top-hd" style={{marginBottom:'10px'}}><a href="http://www.parllay.cn/billboards/" style={{color:'#fff'}} target="_blank">{message?message:isAuditing&&!len?'No photos need to approve 没有未处理的照片':'Powered by Parllay 跨屏朋友圈'}</a></center>}
					{listHtml}
				</div>
			</div>
		)
	}
});

var MainListItem = React.createClass({
	mixins:[ListItemMixin()],
	getInitialState:function(){
		var model=_.clone(this.props.model);

		this.refresh();

		return {
			time:moment(new Date(_.min([model.timestamp,Date.now()-45000]))).fromNow(),
			isLiking:false,
			is_liked:model.is_liked,
			likes:model.likes,
			comments:model.comments_count || 0,
			isShowComment:false,
			showLikeAnimation:false
		}
	},
	shouldComponentUpdate:function(nextProps, nextState){
		return JSON.stringify(this.props.position)!=JSON.stringify(nextProps.position) || !this.props.isAnimating
	},
	/*preview:function(){
		var model=this.props.model,
			imgList=_.map(this.props.collection.toJSON(),function(i){
				return 'http:'+i.photo_url
			});

		if(isWxReady){
			wx.previewImage({
	            current:'http:'+model.photo_url,
	            urls:imgList
	        })
		}
	},*/
	componentDidMount:function(){
		this.componentDidUpdate()
	},
	componentDidUpdate:function(){
		var model=this.props.model;

		if(!model.h && model.ratio){
			this.loaded(model.ratio)
		}
	},
	loaded:function(e){
		var self=this,
			model=this.props.model,
			backboneModel=this.props.backboneModel,
			ele=$(this.refs.item),
			ratio=(typeof e=='object')?(e.target.height/e.target.width).toFixed(2):e,
			isPhone=this.props.isPhone;

		if((!model.width || !model.height) && !isPhone){
			if(!this.ajax){
				this.ajax=$.ajax({
					url:(model.isVideo?model.poster:model.photo_url).split('?')[0]+'?imageInfo',
					dataType:'json',
					success:function(info){
						if(info){
							backboneModel.set({
								width:info.width,
								height:info.height
							})
						}
						self.ajax=null
					},
					error:function(){
						self.ajax=null
					}
				})
			}
		}

		backboneModel.set({
			h:!isPhone?ele.outerHeight(true):null,
			ratio:ratio
		})	
		
	},
	openActionSheet:function(){
		var model=this.props.model;

		this.props.app.react.setState({
			actionSheet:{
				list:model.additional_url?[{
					name:'详情',
					href:model.additional_url
				}]:[]
			}
		})
	},
	showComment:function(){
		this.setState({
			isShowComment:!this.state.isShowComment
		})
	},
	clickTimer:0,
	doubleClick:function(){
		var self=this;
		this.clickTimer++;

        this.dbClickTimer=setTimeout(function () {
            self.clickTimer = 0
        }, 500);
        if (self.clickTimer > 1) {
            self.like();
            self.clickTimer = 0
        }
	},
	resetDbClick:function(){
		clearTimeout(this.dbClickTimer)
		this.clickTimer=0
	},
	render:function(){
		var app=this.props.app,
			model=this.props.model,
			index=this.props.index,
			wallColor=this.props.wallColor,
			isAuditing=this.props.isAuditing,
			checked=this.state.checked,
			time=this.state.time,
			isLiking=this.state.isLiking,
			is_liked=this.state.is_liked,
			likes=this.state.likes,
			comments=this.state.comments,
			position=this.props.position,
			isPhone=this.props.isPhone,
			Plan=typeof plan!='undefined'?plan:null,
			allowLike=(Plan && Plan.features) ? Plan.features.allow_like : false,
			allowComment=(Plan && Plan.features) ? Plan.features.allow_comment : false,
			allowExternalLink=(Plan && Plan.features) ? Plan.features.allow_external_link : false,
			contentAudit=(Plan && Plan.features) ? Plan.features.content_audit : false,
			photoUrl=model.isVideo?model.poster:model.photo_url,
			bodyWidth=parseInt(document.body.clientWidth),
			waterMark='', //'&watermark/2/text/UEFSTExZ/fontsize/'+bodyWidth*2.5+'/font/5a6L5L2T/fill/d2hpdGU=/dissolve/50/gravity/SouthEast/dx/20/dy/20',
			param = photoUrl.indexOf('?')>0?('&imageView2/3/w/'+bodyWidth+waterMark):('?imageView2/3/w/'+bodyWidth+waterMark),
			status=this.props.status,
			showLikeAnimation=this.state.showLikeAnimation;

		
		return (
			<div className={model.isVideo?"list_item col-xs-12 list_item_video":"list_item col-xs-12"} style={!isPhone?position?{'position':'absolute','left':position.l,'top':position.t}:{opacity:0}:{}} ref="item" onTouchStart={isPhone && allowLike && !isAuditing?this.doubleClick:null} onTouchMove={isPhone && allowLike && !isAuditing?this.resetDbClick:null}>
				<div className="panel panel-default">
					<div className="panel-heading">
						<img className="img-responsive" src={photoUrl+(isPhone?param:'')} onClick={this.preview} onLoad={!model.h?this.loaded:''} style={{width:'100%',height:model.ratio && !isPhone?model.ratio*236:null,backgroundColor:'#ccc'}} />
						<img className="source_logo" width="32" height="32" src="/images/icons/weixin.png" />
						{model.isVideo?<img className="video_icon" src="/images/icons/play.png" />:''}
					</div>
					<div className="panel-body" style={{color:wallColor}}>
						<p>{model.description}</p>
						<div className="media">
							<div href="javascript:void(0)" className="media-left"><img className="img-circle avatar" src={model.user.profile_image} /></div>
							<div className="media-body text-muted">{model.user.name}</div>
							<span className="media-right text-right like" >
								<span className="create-time">{time}</span>
							</span>
						</div>
						{!isAuditing && isPhone?<div className="media media_auditing">
							<span className="media-left text-left text-muted"></span>
							<span className="media-right text-right text-muted tools" >
								{allowComment?<i className="glyphicon glyphicon-edit glyphiconMargin"  onClick={this.showComment}></i>:null}
								{allowComment?comments || 0:null}
								{allowLike?<i className={is_liked?"glyphicon glyphicon-heart liked":"glyphicon glyphicon-heart-empty"} onClick={this.like}></i>:null}
								{allowLike?likes || 0:null}
								{allowExternalLink && model.additional_url?<a href={model.additional_url} target="_blank" className="glyphicon glyphicon-new-window"></a>:null}
							</span>
						</div>:''}
						<span></span>
						{!isAuditing && isPhone && this.state.isShowComment && allowComment?<ConmmentThree app={app} card={this} photoId={model.id} />:''}
						{isAuditing && contentAudit?<div className="media media_auditing">
							{status!='deleted'?<div className="btn btn-xs btn-default pull-left" onClick={function(){this.handle('delete')}.bind(this)}><i className="glyphicon glyphicon-trash"></i></div>:''}
							{status!='approved'?<div className="btn btn-xs btn-success pull-right" onClick={function(){this.handle('approve')}.bind(this)}><i className="glyphicon glyphicon-ok"></i></div>:''}
							{status!='rejected'?<div className="btn btn-xs btn-danger pull-right" onClick={function(){this.handle('reject')}.bind(this)}><i className="glyphicon glyphicon-remove"></i></div>:''}
						</div>:''}
					</div>
				</div>
				{isPhone && allowLike && showLikeAnimation?<i className={"list_item_overlay glyphicon glyphicon-heart "+(is_liked?"fade-in":"fade-out")}></i>:null}
				{isPhone && index>1 && (index+1)%5==0?<p className="ad-space">- Powered by Parllay 跨屏朋友圈 -</p>:''}
			</div>
		)
	}
});

var MainListPicItem = React.createClass({
	mixins:[ListItemMixin()],
	getInitialState:function(){
		var model=_.clone(this.props.model);

		this.refresh();

		return {
			time:moment(new Date(_.min([model.timestamp,Date.now()-45000]))).fromNow(),
			isLiking:false,
			is_liked:model.is_liked,
			likes:model.likes
		}
	},
	shouldComponentUpdate:function(nextProps, nextState){
		return JSON.stringify(this.props.position)!=JSON.stringify(nextProps.position)
	},
	loaded:function(e){
		var backboneModel=this.props.backboneModel,
			ratio=(e.target.height/e.target.width).toFixed(2);

		backboneModel.set({
			ratio:ratio
		})
	},
	render:function(){
		var model=this.props.model,
			wallColor=this.props.wallColor,
			time=this.state.time,
			isLiking=this.state.isLiking,
			is_liked=this.state.is_liked,
			likes=this.state.likes,
			position=this.props.position,
			isPhone=this.props.isPhone,
			url=model.isVideo?model.poster:model.photo_url,
			className='list_item col-xs-12 list_item_nopadding'+(model.isVideo?' list_item_video':''),
			Plan=typeof plan!='undefined'?plan:null,
			allowLike=(Plan && Plan.features) ? Plan.features.allow_like : false;

		return (
			<div className={className} style={!isPhone?position?{'position':'absolute','left':position.l,'top':position.t,'width':position.w,'height':position.h,backgroundImage:'url('+url+')'}:{opacity:0}:{}} ref="item">
				<div className="panel panel-default" style={{margin:0}}>
					<img className="source_logo" width="32" height="32" src="/images/icons/weixin.png" />
					{model.isVideo?<img className="video_icon" src="/images/icons/play.png" />:''}
					<div className="panel-body panel-body-absolute" style={{color:wallColor}}>
						<div className="media media-pic">
							<div href="javascript:void(0)" className="media-left"><img className="img-circle avatar" src={model.user.profile_image} /></div>
							<div className="media-body text-muted">{model.user.name}<br /><span className="create-time">{time}</span></div>
							{allowLike?<span className="media-right text-right like" >
								<i className="glyphicon glyphicon-heart"></i>{likes || 0}
							</span>:''}
						</div>
					</div>
				</div>
			</div>
		)
	}
});

var MainListGemItem = React.createClass({
	classNames:{
		2:{
			normal:'gem_itme',
			super:'gem_itme super_gem_itme'
		},
		3:{
			normal:'gem_itme gem_itme_block',
			super:'gem_itme gem_itme_block super_gem_itme'
		}
	},
	componentDidMount:function(){
		var model=this.props.model;

		if(!model.ratio){
			var backboneModel=this.props.backboneModel,
				image=new Image();
			image.onLoad=function(){
				var ratio=(image.height/image.width).toFixed(2);

				backboneModel.set({
					ratio:ratio
				})
			}
			image.src=model.photo_url+'?imageView2/2/w/100'
		}
	},
	loaded:function(e){
		var backboneModel=this.props.backboneModel,
			ratio=(typeof e=='object')?(e.target.height/e.target.width).toFixed(2):e;

		backboneModel.set({
			ratio:ratio
		})
	},
	render:function(){
		var model=this.props.model,
			wallMode=this.props.wallMode,
			classNames=this.classNames[wallMode],
			wallColor=this.props.wallColor,
			ratio=model.ratio || 1,
			animateStyle=model.animateStyle || {},
			position=this.props.position || {},
			isPhone=this.props.isPhone,
			style=_.extend({'position':'absolute','left':position.l,'top':position.t,'width':230,'height':230,'marginLeft':0,'marginTop':0},animateStyle),
			bg={'backgroundImage':'url('+(model.isVideo?model.poster:model.photo_url)+')'};

		return (
			<div className={animateStyle.transform=='scale(3)'?classNames.super:classNames.normal} style={style}>
				<div className={model.isVideo?'gem_itme_bg list_item_video':'gem_itme_bg'} style={bg}></div>
				<div className="gem_user_box">
					<div style={{backgroundColor:'#F26236'}}>
						<div className="gem_user_info">
							<h4>{model.description}</h4>
							<p>{model.user.name}</p>
						</div>
					</div>
				</div>
				<img className="gem_avatar" src={model.user.profile_image} />
				{model.isVideo?<img className="video_icon" src="/images/icons/play.png" />:''}
			</div>
		)
	}
});

/*主菜单*/
var Menu = React.createClass({
	menu:[{
		name:'图片墙 Home',
		linkName:'home',
		picName:''
	},{
		name:'传图片 Upload',
		linkName:'photo',
		picName:''
	},{
		name:'审核 Moderate',
		linkName:'auditing',
		picName:''
	},{
		name:'我 Me',
		linkName:'setting',
		picName:''
	}],
	render: function() {
		var app=this.props.app,
			router=this.props.router,
			logo=this.props.logo,
			mainTitle=this.props.mainTitle,
			status=this.props.status;

		return (
			<div className="menu">
				<PCMenu menu={this.menu} app={app} logo={logo} mainTitle={mainTitle} />
				<PhoneMenu menu={this.menu} app={app} router={router} status={status} />
			</div>
		);
	}
});

var PCMenu = React.createClass({
	shouldComponentUpdate:function(nextProps, nextState){
		return false
	},
	render:function(){
		var app=this.props.app,
			menu=this.props.menu,
			logo=this.props.logo,
			mainTitle=this.props.mainTitle;

		return (
			<div className="navbar navbar-default navbar-fixed-top hidden-xs" id="PCMenu">
				<div className="container-fluid">
					{app.isAdmin?<a href={'#'+menu[2].linkName} className="navbar-brand glyphicon glyphicon-pencil pull-right" style={{top:0,marginRight:'20px'}}></a>:''}
					<a href={'#'+menu[0].linkName} className="navbar-brand wall_logo">{logo?<img src={logo} />:(mainTitle || menu[0].name)}</a>
					{(!app.isAnoymous && canUpload)?<a href={'#'+menu[1].linkName} className="navbar-brand glyphicon glyphicon-plus pull-right" style={{top:0,marginRight:'20px'}}></a>:''}
					<a href={'#mixture-setting'} className="navbar-brand glyphicon glyphicon-th-large pull-right" style={{top:0,lineHeight:'22px',marginRight:'20px'}}></a>
					<a href={'#slider-setting'} className="navbar-brand glyphicon glyphicon-facetime-video pull-right" style={{top:0,lineHeight:'22px',marginRight:'20px'}}></a>
					<a href={'#wall-setting'} className="navbar-brand glyphicon glyphicon-th pull-right" style={{top:0,lineHeight:'22px',marginRight:'22px'}}></a>
				</div>
			</div>
		)
	}
});

//alert(navigator.userAgent.toLowerCase());

//{app.isAdmin?<a href={'#'+menu[3].linkName} className="navbar-brand glyphicon glyphicon-wrench pull-right" style={{top:0}}></a>:''}

var PhoneMenu = React.createClass({
	render:function(){
		var app=this.props.app,
			menu=this.props.menu,
			router=this.props.router,
			status=this.props.status || 'pending';
			//console.log(router)
		return (
			<div className="navbar-fixed-bottom visible-xs">
				<div className="weui_tabbar">
			        <a href={'#'+menu[0].linkName} className={router=='mainList' || router=='mainListHot'?"weui_tabbar_item weui_bar_item_on":"weui_tabbar_item"}>
			            <div className="weui_tabbar_icon">
			                <img src={router=='mainList' || router=='mainListHot'?'/images/icons/home2.png':'/images/icons/home1.png'} width="24" height="24" />
			            </div>
			            <p className="weui_tabbar_label">{menu[0].name}</p>
			        </a>
			        {canUpload?<a href={'#'+menu[1].linkName} className={router=='uploadPhoto'?"weui_tabbar_item weui_bar_item_on":"weui_tabbar_item"}>
			            <div className="weui_tabbar_icon">
			                <img src={router=='uploadPhoto'?'/images/icons/upload2.png':'/images/icons/upload1.png'} width="24" height="24" />
			            </div>
			            <p className="weui_tabbar_label">{menu[1].name}</p>
			        </a>:''}
			        {app.isAdmin?<a href={'#'+menu[2].linkName+'/'+status} className={router=='adminAuditing'?"weui_tabbar_item weui_bar_item_on":"weui_tabbar_item"}>
			            <div className="weui_tabbar_icon">
			                <img src={router=='adminAuditing'?'/images/icons/audit2.png':'/images/icons/audit1.png'} width="24" height="24" />
			            </div>
			            <p className="weui_tabbar_label">{menu[2].name}</p>
			        </a>:''}
			        <a href={'#'+menu[3].linkName} className={router=='userSetting'?"weui_tabbar_item weui_bar_item_on":"weui_tabbar_item"}>
					    <div className="weui_tabbar_icon">
					        <span className="glyphicon glyphicon-user" style={{fontSize:'24px'}}></span>
					    </div>
					    <p className="weui_tabbar_label">{menu[3].name}</p>
					</a>
			    </div>
			</div>	
		)
	}
});

//app.isAdmin

/*{app.isAdmin?<a href={'#'+menu[3].linkName} className={router=='adminSetting'?"weui_tabbar_item weui_bar_item_on":"weui_tabbar_item"}>
    <div className="weui_tabbar_icon">
        <span className="glyphicon glyphicon-wrench" style={{fontSize:'24px'}}></span>
    </div>
    <p className="weui_tabbar_label">{menu[3].name}</p>
</a>:''}*/

/*上传图片*/
var UploadPhoto = React.createClass({
	getInitialState:function(){
		return {
			isOpen:false,
			content:'',
			number:0,
			src:null
		}
	},
	showMenu:function(){
		this.setState({
			isOpen:true
		})
	},
	close:function(){
		this.setState({
			isOpen:false
		})
	},
	localId: null,
	takePhoto: function() {
		var self = this;
		this.setState({
			isOpen:false
		});
		if(isWxReady) {
			wx.chooseImage({
			count: 1, // 默认9
			sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有original
			sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: function (res) {
				var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
				self.localId = localIds[0];
				self.setState({
					src:localIds[0]
				})
			}
		});
		}
	},
	chooseImage: function() {
		var self = this;
		this.setState({
			isOpen:false
		});
		if(isWxReady) {
			wx.chooseImage({
				count: 1, // 默认9
				sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有original
				sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
				success: function (res) {
					var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
					self.localId = localIds[0];
					self.setState({
						src:localIds[0]
					})
				}
			});
		}
	},
	saveImage: function() {
		var self=this,
			app=this.props.app,
			tempImg=$(this.refs.tempImg),
			w=parseInt(tempImg.width()),
			h=parseInt(tempImg.height());
		if(!this.localId) {
			alert('请选择或拍摄一张照片');
			return
		}
		/*if(h>w*2){
			alert('您的图片太瘦啦，请换一张');
			return
		}*/
		wx.uploadImage({
			localId: this.localId,
			isShowProgressTips: 1,
			success: function(res) {
				var serverId = res.serverId;
				$('#toast2').show();
				setTimeout(function(){$('#toast2').hide()},3000);
				$.post('/wall/' + wallId + '/photos', {
					serverId: serverId,
					message: self.state.content,
					ratio:(h/w).toFixed(2)
				}, function(data) {
					location.hash='home'
				})
			}
		})
	},
	keyPress:function(e){
		this.setState({
			content:e.target.value,
			number:e.target.value.length
		})
	},
	render:function(){
		var isOpen=this.state.isOpen,
			content=this.state.content,
			number=this.state.number,
			describe=this.props.describe,
			qrCode=this.props.qrCode,
			src=this.state.src;

		return (
			<div className="main main_setting">
				<center className="hd top-hd" style={{color:'#fff',marginBottom:'10px'}}>Powered by Parllay 跨屏朋友圈</center>
				<div className="weui_cells weui_cells_form" style={{marginTop:'0'}}>
					<div className="weui_cell">
			            <div className="weui_cell_bd weui_cell_primary">
			                <div className="weui_uploader">
			                    <div className="weui_uploader_hd weui_cell">
			                        <div className="weui_cell_bd weui_cell_primary">图片上传 Upload picture</div>
			                    </div>
			                    <div className="weui_uploader_bd upload_zone">
			                        <div className="weui_uploader_input_wrp"></div>
			                        <input className="weui_uploader_input" type="button" onClick={this.showMenu} />
			                        {src?<img src={src} ref="tempImg" />:''}
			                    </div>
			                </div>
			            </div>
			        </div>
			        <div className="weui_cell">
			            <div className="weui_cell_bd weui_cell_primary">
			                <textarea className="weui_textarea" placeholder="请输入评论 Comments" maxLength="140" rows="3" value={content} onChange={this.keyPress}></textarea>
			                <div className="weui_textarea_counter"><span>{number}</span>/140</div>
			            </div>
			        </div>
		        </div>
		        
		        <div className="weui_btn_area">
			        <a className="weui_btn weui_btn_primary" href="javascript:" onClick={this.saveImage} id="showTooltips">确定 Submit</a>
			    </div>
			    <div className="weui_cells_tips" style={{marginTop:'10px'}}>{describe}</div>
			    <div className="weui_msg">
			    	{qrCode?<img className="wall_qrcode" src={qrCode} />:''}
			    </div>
			    <div id="actionSheet_wrap" style={{position:'relative',zIndex:1031}}>
				    <div className={isOpen?"weui_mask_transition weui_fade_toggle":"weui_mask_transition"} style={isOpen?{display:'block'}:{display:'none'}} id="mask"></div>
				    <div className={isOpen?"weui_actionsheet weui_actionsheet_toggle":"weui_actionsheet"} id="weui_actionsheet" style={{bottom:'53px'}}>
				        <div className="weui_actionsheet_menu">
				            <div className="weui_actionsheet_cell" onClick={this.takePhoto} >拍照 Take photo</div>
				            <div className="weui_actionsheet_cell" onClick={this.chooseImage} >从手机相册选择 Choose from album</div>
				        </div>
				        <div className="weui_actionsheet_action">
				            <div className="weui_actionsheet_cell" id="actionsheet_cancel" onClick={this.close}>取消</div>
				        </div>
				    </div>
				</div>
			</div>
		)
	}
});

/*管理员设置界面*/
var AdminSetting = React.createClass({
	getInitialState:function(){
		var wrapper=this.props.wrapper,
			mainTitle=wrapper.state.mainTitle,
			describe=wrapper.state.describe,
			logo=wrapper.state.logo,
			qrCode=wrapper.state.qrCode;

		return {
			isOpen:false,
			number:describe.length || 0,
			position:0,
			mainTitle:mainTitle,
			describe:describe,
			logo:logo,
			qrCode:qrCode
		}
	},
	showMenu:function(){
		this.setState({
			isOpen:true
		})
	},
	close:function(){
		this.setState({
			isOpen:false
		})
	},
	titlekeyPress:function(e){
		this.setState({
			mainTitle:e.target.value
		})
	},
	desckeyPress:function(e){
		this.setState({
			describe:e.target.value,
			number:e.target.value.length
		})
	},
	choosePosition:function(position){
		this.setState({
			position:position
		})
	},
	saveImage: function() {
		/*var wrapper=this.props.wrapper;
		wrapper.setState({
			mainTitle:this.state.mainTitle,
			describe:this.state.describe
		});
		location.hash='#home'*/
	},
	render:function(){
		var wrapper=this.props.wrapper,
			isOpen=this.state.isOpen,
			number=this.state.number,
			position=this.state.position,
			mainTitle=this.state.mainTitle,
			describe=this.state.describe,
			logo=this.state.logo,
			qrCode=this.state.qrCode;

		return (
			<div className="main main_setting">
				<div className="weui_cells weui_cells_form">
					<div className="weui_cell">
			            <div className="weui_cell_bd weui_cell_primary">
			                <div className="weui_uploader">
			                    <div className="weui_uploader_hd weui_cell">
			                        <div className="weui_cell_bd weui_cell_primary">LOGO上传</div>
			                    </div>
			                    <div className="weui_uploader_bd upload_zone">
			                        <div className="weui_uploader_input_wrp"></div>
			                        <input className="weui_uploader_input" type="button" onClick={this.showMenu} />
			                        {logo?<img src={logo} ref="tempImg" />:''}
			                    </div>
			                </div>
			            </div>
			        </div>
			    </div>
			    <div className="weui_cells weui_cells_form">
			    	<div className="weui_cell">
				        <div className="weui_cell_bd weui_cell_primary">
				            <input className="weui_input" type="text" placeholder="请输入图片墙名称" value={mainTitle} onChange={this.titlekeyPress} />
				        </div>
				    </div>
			        <div className="weui_cell">
			        	<div className="weui_cell_bd weui_cell_primary">
			                <textarea className="weui_textarea" placeholder="请输入活动说明" maxLength="140" rows="2" value={describe} onChange={this.desckeyPress}></textarea>
			                <div className="weui_textarea_counter"><span>{number}</span>/140</div>
			            </div>
			        </div>
			    </div>
			    <div className="weui_cells weui_cells_form">
					<div className="weui_cell">
			            <div className="weui_cell_bd weui_cell_primary">
			                <div className="weui_uploader">
			                    <div className="weui_uploader_hd weui_cell">
			                        <div className="weui_cell_bd weui_cell_primary">二维码上传</div>
			                    </div>
			                    <div className="weui_uploader_bd upload_zone">
			                        <div className="weui_uploader_input_wrp"></div>
			                        <input className="weui_uploader_input" type="button" onClick={this.showMenu} />
			                        {qrCode?<img src={qrCode} ref="tempImg2" />:''}
			                    </div>
			                </div>
			            </div>
			        </div>
			    </div>
			    <div className="weui_cells_title">二维码位置</div>
		        <div className="weui_cells weui_cells_radio">
			        <label className="weui_cell weui_check_label" htmlFor="x11">
			            <div className="weui_cell_bd weui_cell_primary">
			                <p>左下角</p>
			            </div>
			            <div className="weui_cell_ft">
			                <input type="radio" className="weui_check" name="radio1" id="x11" checked={position==0} onChange={function(){this.choosePosition(0)}.bind(this)} />
			                <span className="weui_icon_checked"></span>
			            </div>
			        </label>
			        <label className="weui_cell weui_check_label" htmlFor="x12">
			            <div className="weui_cell_bd weui_cell_primary">
			                <p>右下角</p>
			            </div>
			            <div className="weui_cell_ft">
			                <input type="radio" name="radio1" className="weui_check" id="x12" checked={position==1} onChange={function(){this.choosePosition(1)}.bind(this)} />
			                <span className="weui_icon_checked"></span>
			            </div>
			        </label>
			    </div>
		        <div className="weui_btn_area">
			        <a className="weui_btn weui_btn_primary weui_btn_disabled" href="javascript:" onClick={this.saveImage}>确定</a>
			    </div>
			    <div id="actionSheet_wrap" style={{position:'relative',zIndex:1031}}>
				    <div className={isOpen?"weui_mask_transition weui_fade_toggle":"weui_mask_transition"} style={isOpen?{display:'block'}:{display:'none'}} id="mask"></div>
				    <div className={isOpen?"weui_actionsheet weui_actionsheet_toggle":"weui_actionsheet"} id="weui_actionsheet">
				        <div className="weui_actionsheet_menu">
				            <div className="weui_actionsheet_cell" onClick={this.takePhoto} >拍照 Take photo</div>
				            <div className="weui_actionsheet_cell" onClick={this.chooseImage} >从手机相册选择 Choose from album</div>
				        </div>
				        <div className="weui_actionsheet_action">
				            <div className="weui_actionsheet_cell" id="actionsheet_cancel" onClick={this.close}>取消</div>
				        </div>
				    </div>
				</div>
			</div>
		)
	}
});

/*分屏方法集合*/
var mixtureControllers={
	'left1-right2':{
		name:'左一右二',
		className:'fullscreen-multiply-three',
		screens:[
			{
				name:'管',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'用',
				type:'fullscreen',
				hasLogo:true,
				data:new CollectionList()
			},
			{
				name:'用',
				type:'fullscreen',
				hasQrcode:true,
				data:new CollectionList()
			}
		],
		handler:function(collection){
			var screens=_.clone(this.screens);

			collection=_.filter(collection.toJSON(),function(i){
				if(i.source=='PC'){
					screens[0].data.add(i);
				}else{
					return true
				}
				return false
			});

			collection.forEach(function(i,index){
				var order=index%2+1;
				screens[order].data.add(i)
			});

			return screens
		}
	},
	'left1-right2-v2':{
		name:'左一右二2',
		className:'fullscreen-multiply-three',
		screens:[
			{
				name:'用',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'管',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'用',
				type:'fullscreen',
				hasQrcode:true,
				data:new CollectionList()
			}
		],
		handler:function(collection){
			var screens=_.clone(this.screens);

			collection=_.filter(collection.toJSON(),function(i){
				if(i.source=='PC'){
					screens[1].data.add(i);
				}else{
					return true
				}
				return false
			});

			collection.forEach(function(i,index){
				var order=index%2;
				screens[!order?order:order+1].data.add(i)
			});

			return screens
		}
	},
	'left1-right2-v3':{
		name:'左一右二3',
		className:'fullscreen-multiply-three',
		screens:[
			{
				name:'用',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'用',
				type:'fullscreen',
				hasLogo:true,
				data:new CollectionList()
			},
			{
				name:'管',
				type:'fullscreen',
				data:new CollectionList()
			}
		],
		handler:function(collection){
			var screens=_.clone(this.screens);

			collection=_.filter(collection.toJSON(),function(i){
				if(i.source=='PC'){
					screens[2].data.add(i);
				}else{
					return true
				}
				return false
			});

			collection.forEach(function(i,index){
				var order=index%2;
				screens[order].data.add(i)
			});

			return screens
		}
	},
	'left2-right1':{
		name:'左二右一',
		className:'fullscreen-multiply-three2',
		screens:[
			{
				name:'用',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'用',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'管',
				type:'fullscreen',
				hasLogo:true,
				hasQrcode:true,
				data:new CollectionList()
			}
		],
		handler:function(collection){
			var screens=_.clone(this.screens);

			collection=_.filter(collection.toJSON(),function(i){
				if(i.source=='PC'){
					screens[2].data.add(i);
				}else{
					return true
				}
				return false
			});

			collection.forEach(function(i,index){
				var order=index%2;
				screens[order].data.add(i)
			});

			return screens
		}
	},
	'left2-right1-v2':{
		name:'左二右一2',
		className:'fullscreen-multiply-three2',
		screens:[
			{
				name:'管',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'用',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'用',
				type:'fullscreen',
				hasLogo:true,
				hasQrcode:true,
				data:new CollectionList()
			}
		],
		handler:function(collection){
			var screens=_.clone(this.screens);

			collection=_.filter(collection.toJSON(),function(i){
				if(i.source=='PC'){
					screens[0].data.add(i);
				}else{
					return true
				}
				return false
			});

			collection.forEach(function(i,index){
				var order=index%2+1;
				screens[order].data.add(i)
			});

			return screens
		}
	},
	'left2-right1-v3':{
		name:'左二右一3',
		className:'fullscreen-multiply-three2',
		screens:[
			{
				name:'用',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'管',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'用',
				type:'fullscreen',
				hasLogo:true,
				hasQrcode:true,
				data:new CollectionList()
			}
		],
		handler:function(collection){
			var screens=_.clone(this.screens);

			collection=_.filter(collection.toJSON(),function(i){
				if(i.source=='PC'){
					screens[1].data.add(i);
				}else{
					return true
				}
				return false
			});

			collection.forEach(function(i,index){
				var order=index%2;
				screens[!order?order:order+1].data.add(i)
			});

			return screens
		}
	},
	'top1-bottom4':{
		name:'上一下四',
		className:'fullscreen-multiply-five',
		screens:[
			{
				name:'管',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'用',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'用',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'用',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'用',
				type:'fullscreen',
				data:new CollectionList()
			}
		],
		handler:function(collection){
			var screens=_.clone(this.screens);

			collection=_.filter(collection.toJSON(),function(i){
				if(i.source=='PC'){
					screens[0].data.add(i);
				}else{
					return true
				}
				return false
			});

			collection.forEach(function(i,index){
				var order=index%4+1;
				screens[order].data.add(i)
			});

			return screens
		}
	},
	'top1-bottom4-v2':{
		name:'上一下四2',
		className:'fullscreen-multiply-five',
		screens:[
			{
				name:'用',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'管',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'管',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'管',
				type:'fullscreen',
				data:new CollectionList()
			},
			{
				name:'管',
				type:'fullscreen',
				data:new CollectionList()
			}
		],
		handler:function(collection){
			var screens=_.clone(this.screens);

			collection=_.filter(collection.toJSON(),function(i){
				if(i.source!='PC'){
					screens[0].data.add(i);
				}else{
					return true
				}
				return false
			});

			collection.forEach(function(i,index){
				var order=index%4+1;
				screens[order].data.add(i)
			});

			return screens
		}
	}
};

/*分屏播放*/
var MixturePlayer = React.createClass({
	render:function(){
		var app=this.props.app,
			isPhone=this.props.isPhone,
			collection=this.props.collection,
			mixtureMode=this.props.mixtureMode,
			mixtureBackground=this.props.mixtureBackground,
			mixtureColor=this.props.mixtureColor,
			mixtureSpeed=this.props.mixtureSpeed,
			sliderSpeedList=this.props.sliderSpeedList,
			wallSpeedList=this.props.wallSpeedList,
			controller=mixtureControllers[mixtureMode],
			screens=controller.handler(collection);

		return (
			<div className={"giant_screen mixture_screen "+controller.className}>
				{screens.map(function(screen,index){
					if(screen.data.length){
						switch(screen.type){
							case 'waterfall':
								return <WallPlayer key={index} app={app} isPhone={isPhone} collection={screen.data} wallMode={0} wallBackground={mixtureBackground} wallColor={mixtureColor} wallSpeed={mixtureSpeed} wallSpeedList={wallSpeedList} hasLogo={screen.hasLogo} />;
								break;
							case 'pearls':
								return <GemPlayer key={index} app={app} isPhone={isPhone} collection={screen.data} wallMode={2} wallBackground={mixtureBackground} wallColor={mixtureColor} wallSpeed={mixtureSpeed} wallSpeedList={wallSpeedList} hasLogo={screen.hasLogo} />;
								break;
							case 'fullscreen':
								return <SliderPlayer key={index} app={app} collection={screen.data} sliderMode={1} sliderBackground={mixtureBackground} sliderColor={mixtureColor} sliderSpeed={mixtureSpeed} sliderSpeedList={sliderSpeedList} hasLogo={screen.hasLogo} hasQrcode={screen.hasQrcode} />;
								break;
						}
					}else{
						return <div key={index}></div>
					}
				})}
			</div>
		)
	}
});

/*视频播放器*/
var VideoPlayer = React.createClass({
	videoLoaded:function(e){
		e.target.play()
	},
	render:function(){
		var model=this.props.model,
			callback=this.props.callback;

		return (
			<video style={{backgroundColor:'#333'}} src={model.photo_url} autoPlay onCanPlay={this.videoLoaded} onEnded={callback} width="100%" height="100%"></video>
		)
	}
});

/*幻灯片*/
var SliderPlayer = React.createClass({
	getInitialState:function(){
		return {
			cur:0
		}
	},
	last:-1,
	dir:0,
	componentDidMount:function(){
		//this.componentDidUpdate()
	},
	shouldComponentUpdate:function(nextProps, nextState){
		/*if(this.isloaded){
			console.log(this.state.cur +' - '+ nextState.cur)
			return this.state.cur != nextState.cur
		}else{
			this.isloaded=true;
			return true
		}*/
		return this.state.cur != nextState.cur
	},
	playNext:function(){
		var self=this,
			app=this.props.app,
			cur=this.state.cur,
			collection=this.props.collection,
			next=collection.at(cur+1);

		this.last=cur;
		this.setState({
			cur:next?cur+1:0
		});

		if(!next && cur==0){
			this.forceUpdate()
		}
	},
	close:function(){
		location.hash='#home'
	},
	render:function(){
		var self=this,
			cur=this.state.cur,
			collection=this.props.collection,
			model=collection.at(cur)?collection.at(cur).toJSON():null,
			last=collection.at(this.last)?collection.at(this.last).toJSON():null,
			sliderMode=this.props.sliderMode,
			sliderBackground=this.props.sliderBackground,
			hasLogo=this.props.hasLogo,
			hasQrcode=this.props.hasQrcode;

		return (
			<div className="giant_screen" onClick={this.close} style={{backgroundColor:sliderBackground}}>
				{model?(function(){
					switch(sliderMode){
						case 0:
							switch(self.dir){
								case 0:
									self.dir=1;
									return <Effect1 model={model} slider={self} hasLogo={hasLogo} />;
									break;
								case 1:
									self.dir=0;
									return <Effect2 model={model} slider={self} hasLogo={hasLogo} />;
									break;
							}
							break;
						case 1:
							return <Effect3 model={model} slider={self} last={last} hasLogo={hasLogo} hasQrcode={hasQrcode} />;
							break;
						case 2:
							return <Effect4 model={model} slider={self} last={last} cur={cur} />;
							break;
					}
					
				})():''}
			</div>
		)
	}
});

/*幻灯效果一*/
var Effect1 = React.createClass({
	getInitialState:function(){
		return {
			animateStyle:{}
		}
	},
	componentDidMount:function(){
		var self=this,
			slider=this.props.slider,
			model=this.props.model,
			ratio=model.ratio,
			w=$(this.refs.giant_screen_img).width(),
			h=$(this.refs.giant_screen_img).height(),
			sliderSpeedMin=slider.props.sliderSpeedList[slider.props.sliderSpeed].val/1000,
			sliderSpeed=sliderSpeedMin/500,
			animateStyle={
				backgroundImage:'url('+model.photo_url+')',
				transitionTimingFunction:'linear',
				MozTransitionTimingFunction:'linear',
				WebkitTransitionTimingFunction:'linear',
				OTransitionTimingFunction:'linear',
				MsTransitionTimingFunction:'linear'
			},
			imgWidth=w+'px',
			imgHeight=h+'px',
			transform='translate(0,0)',
			duration=sliderSpeedMin;
		
		if(!model.isVideo){
			if(ratio){
				if(ratio>h/w){
					imgHeight=w*ratio+'px';
					transform='translate(0,'+(h-w*ratio)+'px)';
					duration=_.max([(w*ratio-h)*sliderSpeed,duration])
				}else{
					imgWidth=h/ratio+'px';
					transform='translate('+(w-h/ratio)+'px,0)';
					duration=_.max([(h/ratio-w)*sliderSpeed,duration])
				}
			}

			setTimeout(function(){
				self.setState({
					animateStyle:{
						backgroundImage:'url('+model.photo_url+')',
						width:imgWidth,
						height:imgHeight
					}
				},function(){
					setTimeout(function(){
						self.setState({
							animateStyle:_.extend(animateStyle,{
								width:imgWidth,
								height:imgHeight,
								transform:transform,
								MozTransform:transform,
								WebkitTransform:transform,
								OTransform:transform,
								MsTransform:transform,
								transitionDuration:duration+'s',
								MozTransitionDuration:duration+'s',
								WebkitTransitionDuration:duration+'s',
								OTransitionDuration:duration+'s',
								MsTransitionDuration:duration+'s'
							})
						})
					},0)

					setTimeout(function(){
						slider.playNext()
					},duration*1000+1000)
				})
			})
		}
	},
	render:function(){
		var slider=this.props.slider,
			model=this.props.model,
			sliderColor=slider.props.sliderColor,
			animateStyle=this.state.animateStyle,
			hasLogo=this.props.hasLogo,
			Plan=typeof plan!='undefined'?plan:null,
			isHideLogo=(Plan && Plan.features) ? Plan.features.is_hide_parllay_logo : false;

		return (
			<div className="row giant_screen_row" style={{color:sliderColor}}>
				<div className="col-sm-8 giant_screen_pic">
					<div ref="giant_screen_img">
						{!model.isVideo?<div style={animateStyle}></div>:<VideoPlayer model={model} callback={slider.playNext} />}
					</div>
				</div>
				<div className="col-sm-4 giant_screen_right">
					<h1 className="giant_screen_title">{model.description}</h1>
					<div className="media">
						<div href="javascript:void(0)" className="media-left"><img className="img-circle avatar" src={model.user.profile_image} /></div>
						<h4 className="media-body text-muted">{model.user.name}<br /><span className="create-time">{moment(new Date(model.timestamp)).fromNow()}</span></h4>
						<h4 className="media-right text-right text-muted source_logo" ><img width="48" height="48" src="/images/icons/weixin.png" /></h4>
					</div>
				</div>
				{hasLogo?<img className="parllay_logo" src={!isHideLogo?"/dashboard/images/sign-in-logo.png":wallLogo} />:''}
			</div>
		)
	}
});

/*幻灯效果二*/
var Effect2 = React.createClass({
	getInitialState:function(){
		return {
			animateStyle:{}
		}
	},
	componentDidMount:function(){
		var self=this,
			slider=this.props.slider,
			model=this.props.model,
			ratio=model.ratio,
			w=$(this.refs.giant_screen_img).width(),
			h=$(this.refs.giant_screen_img).height(),
			sliderSpeedMin=slider.props.sliderSpeedList[slider.props.sliderSpeed].val/1000,
			sliderSpeed=sliderSpeedMin/500,
			animateStyle={
				backgroundImage:'url('+model.photo_url+')',
				transitionTimingFunction:'linear',
				MozTransitionTimingFunction:'linear',
				WebkitTransitionTimingFunction:'linear',
				OTransitionTimingFunction:'linear',
				MsTransitionTimingFunction:'linear'
			},
			imgWidth=w+'px',
			imgHeight=h+'px',
			transform='translate(0,0)',
			duration=sliderSpeedMin;
		
		if(!model.isVideo){
			if(ratio){
				if(ratio>h/w){
					imgHeight=w*ratio+'px';
					transform='translate(0,'+(h-w*ratio)+'px)';
					duration=_.max([(w*ratio-h)*sliderSpeed,duration])
				}else{
					imgWidth=h/ratio+'px';
					transform='translate('+(w-h/ratio)+'px,0)';
					duration=_.max([(h/ratio-w)*sliderSpeed,duration])
				}
			}

			setTimeout(function(){
				self.setState({
					animateStyle:{
						backgroundImage:'url('+model.photo_url+')',
						width:imgWidth,
						height:imgHeight
					}
				},function(){
					setTimeout(function(){
						self.setState({
							animateStyle:_.extend(animateStyle,{
								width:imgWidth,
								height:imgHeight,
								transform:transform,
								MozTransform:transform,
								WebkitTransform:transform,
								OTransform:transform,
								MsTransform:transform,
								transitionDuration:duration+'s',
								MozTransitionDuration:duration+'s',
								WebkitTransitionDuration:duration+'s',
								OTransitionDuration:duration+'s',
								MsTransitionDuration:duration+'s'
							})
						})
					},0)

					setTimeout(function(){
						slider.playNext()
					},duration*1000+1000)
				})
			})
		}
	},
	render:function(){
		var slider=this.props.slider,
			model=this.props.model,
			sliderColor=slider.props.sliderColor,
			animateStyle=this.state.animateStyle,
			hasLogo=this.props.hasLogo,
			Plan=typeof plan!='undefined'?plan:null,
			isHideLogo=(Plan && Plan.features) ? Plan.features.is_hide_parllay_logo : false;

		return (
			<div className="row giant_screen_row" style={{color:sliderColor}}>
				<div className="col-sm-4 giant_screen_right giant_screen_left">
					<h1 className="giant_screen_title">{model.description}</h1>
					<div className="media">
						<div href="javascript:void(0)" className="media-left"><img className="img-circle avatar" src={model.user.profile_image} /></div>
						<h4 className="media-body text-muted">{model.user.name}<br /><span className="create-time">{moment(new Date(model.timestamp)).fromNow()}</span></h4>
						<h4 className="media-right text-right text-muted source_logo" ><img width="48" height="48" src="/images/icons/weixin.png" /></h4>
					</div>
				</div>
				<div className="col-sm-8 giant_screen_pic">
					<div ref="giant_screen_img">
						{!model.isVideo?<div style={animateStyle}></div>:<VideoPlayer model={model} callback={slider.playNext} />}
					</div>
				</div>
				{hasLogo?<img className="parllay_logo" src={!isHideLogo?"/dashboard/images/sign-in-logo.png":wallLogo} />:''}
			</div>
		)
	}
});

/*幻灯效果三*/
var Effect3 = React.createClass({
	getInitialState:function(){
		return {
			animateStyle:{}
		}
	},
	componentDidMount:function(){
		this.componentWillReceiveProps(this.props)
	},
	componentWillReceiveProps:function(props){
		var self=this,
			slider=props.slider,
			model=props.model,
			ratio=model.ratio,
			w=$(this.refs.giant_screen_img).width(),
			h=$(this.refs.giant_screen_img).height(),
			sliderSpeedMin=slider.props.sliderSpeedList[slider.props.sliderSpeed].val/1000,
			sliderSpeed=sliderSpeedMin/500,
			animateStyle={
				backgroundImage:'url('+model.photo_url+')',
				transitionTimingFunction:'linear',
				MozTransitionTimingFunction:'linear',
				WebkitTransitionTimingFunction:'linear',
				OTransitionTimingFunction:'linear',
				MsTransitionTimingFunction:'linear'
			},
			imgWidth=w,
			imgHeight=h,
			transform='translate(0,0)',
			duration=sliderSpeedMin;
		
		if(!model.isVideo){
			if(ratio){
				if(ratio>h/w){
					imgHeight=w*ratio;
					transform='translate(0,'+(h-w*ratio)+'px)';
					duration=_.max([(w*ratio-h)*sliderSpeed,duration])
				}else{
					imgWidth=h/ratio;
					transform='translate('+(w-h/ratio)+'px,0)';
					duration=_.max([(h/ratio-w)*sliderSpeed,duration])
				}
			}
			
			setTimeout(function(){
				self.setState({
					animateStyle:{
						backgroundImage:'url('+model.photo_url+')',
						width:imgWidth,
						height:imgHeight
					}
				},function(){
					setTimeout(function(){
						self.setState({
							animateStyle:_.extend(animateStyle,{
								width:imgWidth,
								height:imgHeight,
								transform:transform,
								MozTransform:transform,
								WebkitTransform:transform,
								OTransform:transform,
								MsTransform:transform,
								transitionDuration:duration+'s',
								MozTransitionDuration:duration+'s',
								WebkitTransitionDuration:duration+'s',
								OTransitionDuration:duration+'s',
								MsTransitionDuration:duration+'s'
							})
						})
					});
					
					self.timer=setTimeout(function(){
						self.setState({
							animateStyle:false
						},function(){
							self.playNext()
						})
					},duration*1000+1000)
				})
			})
		}
	},
	playNext:function(){
		var slider=this.props.slider;
		slider.playNext()
	},
	componentWillUnmount:function(){
		clearTimeout(this.timer)
	},
	render:function(){
		var model=this.props.model,
			last=this.props.last,
			sliderColor='#fff',
			animateStyle=this.state.animateStyle,
			hasLogo=this.props.hasLogo,
			hasQrcode=this.props.hasQrcode,
			Plan=typeof plan!='undefined'?plan:null,
			isHideLogo=(Plan && Plan.features) ? Plan.features.is_hide_parllay_logo : false;

		return (
			<div className="giant_screen_row full_background_screen" ref="giant_screen_img" style={{color:sliderColor}}>
				{!model.isVideo?animateStyle?<div>
					<div className="giant_screen_background" style={animateStyle} ></div>
					<div className="media">
						<div href="javascript:void(0)" className="media-left"><img className="img-circle avatar" src={model.user.profile_image} /></div>
						<h4 className="media-body">{model.user.name}<br /><span className="create-time">{moment(new Date(model.timestamp)).fromNow()}</span></h4>
						<h4 className="media-right text-right text-muted source_logo" ></h4>
					</div>
					<h1 className="giant_screen_title"><img width="48" height="48" src="/images/icons/weixin.png" />{model.description}</h1>
					{hasLogo?<img className="parllay_logo" src={!isHideLogo?"/dashboard/images/sign-in-logo.png":wallLogo} />:''}
					{hasQrcode && wallQrcode?<img className="parllay_qrcode" src={wallQrcode} />:''}
					{hasQrcode && wallQrcode?<div className="follows_us"><p>扫描二维码</p><p>关注我们</p></div>:''}
				</div>:<div><div></div></div>:<VideoPlayer model={model} callback={this.playNext} />}
			</div>
		)
	}
});

/*幻灯效果四*/
var Effect4 = React.createClass({
	getInitialState:function(){
		return {
			model:this.props.model,
			bgColor:this.colorList[0],
			animateMode:'in',
			animateType:'default'
		}
	},
	colorList:['#F26236','#60B2A5','#B2C036','#2f7ed8','#e05f6f'],
	animateStyle:{
		scale:{
			out:{
				transform:'scale(0)',
				MozTransform:'scale(0)',
				WebkitTransform:'scale(0)',
				OTransform:'scale(0)',
				MsTransform:'scale(0)'
			}
		},
		rotate:{
			out:{
				transform:'rotateY(90deg)',
				MozTransform:'rotateY(90deg)',
				WebkitTransform:'rotateY(90deg)',
				OTransform:'rotateY(90deg)',
				MsTransform:'rotateY(90deg)'
			}
		},
		slide:{
			in:[
				{
					transitionDuration:'0s',
					MozTransitionDuration:'0s',
					WebkitTransitionDuration:'0s',
					OTransitionDuration:'0s',
					MsTransitionDuration:'0s'
				},
				{
					transitionDuration:'0s',
					MozTransitionDuration:'0s',
					WebkitTransitionDuration:'0s',
					OTransitionDuration:'0s',
					MsTransitionDuration:'0s',
					visibility:'hidden'
				}
			],
			out:[
				{
					transform:'translate(0,-100%)',
					MozTransform:'translate(0,-100%)',
					WebkitTransform:'translate(0,-100%)',
					OTransform:'translate(0,-100%)',
					MsTransform:'translate(0,-100%)',
					transitionTimingFunction:'ease-in-out',
					MozTransitionTimingFunction:'ease-in-out',
					WebkitTransitionTimingFunction:'ease-in-out',
					OTransitionTimingFunction:'ease-in-out',
					MsTransitionTimingFunction:'ease-in-out'
				},
				{
					transform:'translate(0,-100%)',
					MozTransform:'translate(0,-100%)',
					WebkitTransform:'translate(0,-100%)',
					OTransform:'translate(0,-100%)',
					MsTransform:'translate(0,-100%)',
					transitionTimingFunction:'ease-in-out',
					MozTransitionTimingFunction:'ease-in-out',
					WebkitTransitionTimingFunction:'ease-in-out',
					OTransitionTimingFunction:'ease-in-out',
					MsTransitionTimingFunction:'ease-in-out',
					transitionDuration:'0.4s',
					MozTransitionDuration:'0.4s',
					WebkitTransitionDuration:'0.4s',
					OTransitionDuration:'0.4s',
					MsTransitionDuration:'0.4s'
				}
			]
		},
		fade:{
			out:{
				
			}
		},
		default:{
			transform:'none',
			MozTransform:'none',
			WebkitTransform:'none',
			OTransform:'none',
			MsTransform:'none'
		}
	},
	animateDuration:{
		transitionDuration:'0.5s',
		MozTransitionDuration:'0.5s',
		WebkitTransitionDuration:'0.5s',
		OTransitionDuration:'0.5s',
		MsTransitionDuration:'0.5s',
	},
	typeList:['scale','rotate','slide','fade'],
	componentDidMount:function(){
		this.componentWillReceiveProps(this.props)
	},
	componentWillReceiveProps:function(props){
		var self=this,
			slider=this.props.slider,
			cur=props.cur,
			colorList=this.colorList,
			len=cur%colorList.length,
			bg=colorList[len],
			lastBg=colorList[len?len-1:colorList.length-1],
			type=this.typeList[Math.floor(Math.random()*4)], //Math.floor(Math.random()*3)
			sliderSpeed=slider.props.sliderSpeedList[slider.props.sliderSpeed].val/1000;

		if(!this.state.model.isVideo){
			if(props.last){
				this.setState({
					animateMode:'out',
					animateType:type
				},function(){
					setTimeout(function(){
						self.setState({
							model:props.model,
							bgColor:bg,
							animateMode:'in',
							animateType:type
						})
					},500)
				})
			}else{
				this.setState({
					model:props.model,
					bgColor:bg,
					animateMode:'in',
					animateType:type
				})
			}

			setTimeout(function(){
				slider.playNext()
			},sliderSpeed*1000+1000)
		}else{
			setTimeout(function(){
				self.setState({
					model:props.model,
					bgColor:bg,
					animateMode:'in',
					animateType:type
				})
			},0)
		}
	},
	render:function(){
		var model=this.state.model || {user:{}},
			nextModel=this.props.model || {user:{}},
			slider=this.props.slider,
			bgColor=this.state.bgColor,
			cur=this.props.cur,
			colorList=this.colorList,
			len=cur%colorList.length,
			nextBg=colorList[len],
			type=this.state.animateType,
			duration=this.animateDuration,
			animate=this.animateStyle[type][this.state.animateMode] || this.animateStyle['default'],
			sliderColor='#fff';
		
		return (
			<div className="giant_screen_row atmosphere_screen" style={{color:sliderColor}}>
				{animate instanceof Array?[<div key={1} className="atmosphere img-circle" style={_.extend({borderColor:bgColor},duration,animate[0])}>
					{!model.isVideo?<div className="atmosphere-photo" style={{backgroundImage:'url('+model.photo_url+')'}}></div>:<VideoPlayer model={model} callback={slider.playNext} />}
					<div className="atmosphere-userinfo" style={{backgroundColor:bgColor}}>
						<img src={model.user.profile_image} />
						<h4>{model.user.name}</h4>
						<h4 className="atmosphere_desc">{model.description}</h4>
					</div>
				</div>,<div key={2} className="atmosphere img-circle" style={_.extend({borderColor:bgColor},duration,animate[1])}>
					<div className="atmosphere-photo" style={{backgroundImage:'url('+nextModel.photo_url+')'}}></div>
					<div className="atmosphere-userinfo" style={{backgroundColor:nextBg}}>
						<img src={nextModel.user.profile_image} />
						<h4>{nextModel.user.name}</h4>
						<h4 className="atmosphere_desc">{nextModel.description}</h4>
					</div>
				</div>]:[<div key={1} className="atmosphere img-circle" style={_.extend({borderColor:bgColor},duration,animate)}>
					{!model.isVideo?<div className="atmosphere-photo" style={_.extend(type=='fade'?duration:{},{backgroundImage:'url('+model.photo_url+')'})}></div>:<VideoPlayer model={model} callback={slider.playNext} />}
					<div className="atmosphere-userinfo" style={{backgroundColor:bgColor}}>
						<img src={model.user.profile_image} />
						<h4>{model.user.name}</h4>
						<h4 className="atmosphere_desc">{model.description}</h4>
					</div>
				</div>,<div key={2} className="atmosphere img-circle" style={{visibility:'hidden'}}></div>]}
			</div>
		)
	}
});

/*瀑布流一屏*/
var LoadItemsWithoutSize = React.createClass({
	render:function(){
		var collection=this.props.collection.models;

		return (
			<div className="main" style={{'position':'fixed','left':'-9999px'}}>
				{collection.map(function(i,index){
					var model=i.toJSON();
					if(!model.ratio || !model.h){
						return <MainListItem key={model.id} model={model} backboneModel={i} index={index} />;
					}
				})}
			</div>
		)
	}
});

/*瀑布流滚动*/
var WallPlayer = React.createClass({
	mixins:[WaterFaller()],
	getInitialState:function(){

		return {
			listArray:this.props.collection.toJSON(),
			mainTop:0,
			tranStyle:{}
		}
	},
	shouldComponentUpdate:function(nextProps, nextState){
		var state=this.state;
		return (state.mainTop!=nextState.mainTop)  //(state.listArray.length!=nextState.listArray.length) || (state.mainTop!=nextState.mainTop)
	},
	componentDidMount:function(){
		this.animationStart()
	},
	close:function(){
		clearTimeout(this.timer);
		this.timer=null;
		location.hash='#home'
	},
	render:function(){
		var app=this.props.app,
			isAuditing=this.props.isAuditing,
			wallMode=isAuditing?0:this.props.wallMode,
			wallBackground=this.props.wallBackground,
			wallColor=this.props.wallColor,
			collection=this.props.collection,
			listArray=this.state.listArray,
			isPhone=this.props.isPhone,
			listHtml=[],
			mainTop=this.state.mainTop,
			transform='translate(0px,'+mainTop+'px)',
			tranStyle=this.state.tranStyle,
			hasLogo=this.props.hasLogo,
			layout=this.getLayout(),
			className='main giant_screen',
			Plan=typeof plan!='undefined'?plan:null,
			isHideLogo=(Plan && Plan.features) ? Plan.features.is_hide_parllay_logo : false;

			className+=wallMode==4?' main-sizelimit':'';

			listArray.forEach(function(model,index){
				switch (wallMode){
					case 0:
						listHtml.push(<MainListItem isAnimating={true} key={index} isPhone={isPhone} position={layout[index]} app={app} model={model} backboneModel={collection.get(model.id)} index={index} wallColor={wallColor} isAuditing={isAuditing} />);
						break;
					case 1:
					case 4:
						listHtml.push(<MainListPicItem key={index} isPhone={isPhone} position={layout[index]} model={model} backboneModel={collection.get(model.id)} index={index} wallColor={wallColor} />);
						break;
				}
			});	

		return (
			<div className={className} onClick={this.close} style={{backgroundColor:wallBackground}}>
				<div id="main" ref="giant_screen" style={_.extend({height:_.max(this.tempArr),transform:transform,'MozTransform':transform,'WebkitTransform':transform,'OTransform':transform,'MsTransform':transform},tranStyle)}>
					{listHtml}
				</div>
				{hasLogo?<img className="parllay_logo" src={!isHideLogo?"/dashboard/images/sign-in-logo.png":wallLogo} />:''}
			</div>
		)
	}
});

/*宝石阵*/
var GemPlayer = React.createClass({
	getInitialState:function(){
		return {
			listArray:[]
		}
	},
	componentDidMount:function(){
		this.animationStart()
	},
	counter:0,
	animationStart:function(){
		var self=this,
			collection=this.props.collection.toJSON(),
			listArray=this.state.listArray,
			len=listArray.length,
			wallSpeed=this.props.wallSpeedList[this.props.wallSpeed].val,
			isPhone=this.props.isPhone,
			colNum=$('#main')&&!isPhone?Math.floor($('#main').width()/250):1,
			rowNum=!isPhone?Math.ceil(($('body').height()-65)/250):1,
			screenMaxGemLength=colNum*(rowNum+1);

		console.log(colNum+' , '+rowNum)
		listArray=listArray.concat(this.getNewRow(screenMaxGemLength-len));

		this.highlightItem=null;
		
		this.setState({
			listArray:listArray
		},function(){

			switch(self.counter){
				case 3:
					listArray=self.highlight(listArray,colNum,rowNum);
					break;
				case 4:
					listArray=self.highlight(listArray,colNum,rowNum,true);
					break;
				default:
					listArray=self.normalMove(listArray,colNum);
					break
			}

			setTimeout(function(){
				self.setState({
					listArray:listArray
				},function(){
					if(this.highlightItem){
						self.timer=setTimeout(function(){
							self.animationNext(listArray,colNum)
						},8000/wallSpeed)
					}else{
						self.timer=setTimeout(function(){
							self.animationNext(listArray,colNum)
						},8000/wallSpeed)
					}
				});
				//$(self.refs.temp).text('totalJSHeapSize:'+performance.memory.totalJSHeapSize+' , '+'usedJSHeapSize:'+performance.memory.usedJSHeapSize+' , '+'jsHeapSizeLimit:'+performance.memory.jsHeapSizeLimit)
			},0)
			
		})

	},
	animationNext:function(listArray,colNum){
		if(this.counter<4){
			listArray.splice(0,colNum);

			listArray.map(function(i,index){
				i.animateStyle={};
				return i
			});

			this.setState({
				listArray:listArray
			},function(){
				this.animationStart()
			}.bind(this))
		}else{
			this.animationStart()
		}
	},
	getNewRow:function(number){
		var collection=this.props.collection,
			collectionArr=collection.toJSON(),
			len=collection.length,
			lastGemId=this.lastGemId,
			lastGemIndex=lastGemId?_.findIndex(collectionArr,function(i){ return i.id==lastGemId}):0,
			result=[];

		while(number>0){
			var targetIndex=_.min([lastGemIndex+number,len]);
			result=result.concat(collectionArr.slice(lastGemIndex,targetIndex));
			number=number-(targetIndex-lastGemIndex);
			lastGemIndex=targetIndex==len?0:targetIndex
		}
		this.lastGemId=collection.at(lastGemIndex).get('id');

		return result
	},
	highlight:function(listArray,colNum,rowNum,isShrink){
		var point=this.highlightPoint,
			x=isShrink?point.x:Math.round(1+(colNum-3>0?colNum-3:0)*Math.random()),
			y=isShrink?point.y:Math.round(1+(rowNum-4>0?rowNum-4:0)*Math.random()),
			fromPoint=[x*250+125,y*250+125],
			maxDistance=0;
		
		listArray.forEach(function(i,index){
			var itemX=index%colNum,
				itemY=parseInt(index/colNum);

			if(itemX==x || itemY==y){
				var itemCenter = this.getViewportCenter(itemX,itemY),
					distance = this.distance(itemCenter, fromPoint);

				if (distance > maxDistance) {
					maxDistance = distance;
				}
			}
		}.bind(this));

		listArray=_.map(listArray,function(i,index){
			var itemX=index%colNum,
				itemY=parseInt(index/colNum),
				i=_.clone(i);

			if((Math.abs(itemX-x)<2 && itemY-y==0) || Math.abs(itemY-y)<2){
				var itemCenter = this.getViewportCenter(itemX,itemY),
				  	distance = this.distance(itemCenter, fromPoint),
					scaledDistance = distance / maxDistance,
				 	duration = 3 * scaledDistance;
				if(itemX==x && itemY==y){
					if(!isShrink){this.highlightPoint={x:itemX,y:itemY}}
					this.highlightItem=i.id;

					i.animateStyle={
						transitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
						MozTransitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
						WebkitTransitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
						OTransitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
						MsTransitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
						width:230,
						height:230,
						transitionDuration:1+'s',
						MozTransitionDuration:1+'s',
						WebkitTransitionDuration:1+'s',
						OTransitionDuration:1+'s',
						MsTransitionDuration:1+'s',
						transitionProperty:'transform width height',
						MozTransitionProperty:'transform width height',
						WebkitTransitionProperty:'transform width height',
						OTransitionProperty:'transform width height',
						MsTransitionProperty:'transform width height',
						transform:!isShrink?'scale(3)':'scale(1)',
						MozTransform:!isShrink?'scale(3)':'scale(1)',
						WebkitTransform:!isShrink?'scale(3)':'scale(1)',
						OTransform:!isShrink?'scale(3)':'scale(1)',
						MsTransform:!isShrink?'scale(3)':'scale(1)',
						marginLeft:0,
						marginTop:0
					}
				}else{
					var offsetX=(itemX-x>0?1:itemX-x<0?-1:0)*250,
						offsetY=(offsetX?0:itemY-y>0?1:itemY-y<0?-1:0)*250;
					
					i.animateStyle={
						transitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
						MozTransitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
						WebkitTransitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
						OTransitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
						MsTransitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
						transitionDuration:duration+'s',
						MozTransitionDuration:duration+'s',
						WebkitTransitionDuration:duration+'s',
						OTransitionDuration:duration+'s',
						MsTransitionDuration:duration+'s',
						transitionProperty:'transform width height',
						MozTransitionProperty:'transform width height',
						WebkitTransitionProperty:'transform width height',
						OTransitionProperty:'transform width height',
						MsTransitionProperty:'transform width height',
						transform:'translate('+(isShrink?0:offsetX)+'px,'+(isShrink?0:offsetY)+'px)',
						MozTransform:'translate('+(isShrink?0:offsetX)+'px,'+(isShrink?0:offsetY)+'px)',
						WebkitTransform:'translate('+(isShrink?0:offsetX)+'px,'+(isShrink?0:offsetY)+'px)',
						OTransform:'translate('+(isShrink?0:offsetX)+'px,'+(isShrink?0:offsetY)+'px)',
						MsTransform:'translate('+(isShrink?0:offsetX)+'px,'+(isShrink?0:offsetY)+'px)',
						width:230,
						height:230,
						marginLeft:0,
						marginTop:0
					}
				}
			}else{
				i.animateStyle={
					transform:'translate(0px,0px)'
				}
			}

			return i
		}.bind(this));
		
		this.counter++;

		return listArray
	},
	normalMove:function(listArray,colNum){
		var container=this.refs.giant_gem_screen,
			fromPoint=[$(container).width() * Math.round(Math.random()), $(container).height() + 250 * 2.5],
			maxDistance=0;

		listArray.forEach(function(i,index){
			var itemCenter = this.getViewportCenter(index%colNum,parseInt(index/colNum)),
				distance = this.distance(itemCenter, fromPoint);

			if (distance > maxDistance) {
				maxDistance = distance;
			}
		}.bind(this));

		listArray=_.map(listArray,function(i,index){

			var itemCenter = this.getViewportCenter(index%colNum,parseInt(index/colNum)),
			  	distance = this.distance(itemCenter, fromPoint),
				scaledDistance = distance / maxDistance,
			 	duration = 3 * scaledDistance,
			 	i=_.clone(i);
			
			i.animateStyle={
				transitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
				MozTransitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
				WebkitTransitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
				OTransitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
				MsTransitionTimingFunction:'cubic-bezier(0.493, 0, 0.112, 1)',
				transitionDuration:duration+'s',
				MozTransitionDuration:duration+'s',
				WebkitTransitionDuration:duration+'s',
				OTransitionDuration:duration+'s',
				MsTransitionDuration:duration+'s',
				transitionProperty:'transform width height',
				transform:'translate(0px, -250px)',
				MozTransform:'translate(0px, -250px)',
				WebkitTransform:'translate(0px, -250px)',
				OTransform:'translate(0px, -250px)',
				MsTransform:'translate(0px, -250px)',
				width:230,
				height:230,
				marginLeft:0,
				marginTop:0
			};

			return i
		}.bind(this));

		this.counter=this.counter>=5?1:this.counter+1;

		return listArray
	},
	distance: function(point1, point2) {
		var a2 = Math.pow(Math.abs(point1[0] - point2[0]), 2);
		var b2 = Math.pow(Math.abs(point1[1] - point2[1]), 2);
		return Math.round(Math.sqrt(a2 + b2));
	},
	getViewportCenter: function(x,y) {
		return [x*250 + 125, y*250 + 125];
	},
	close:function(){
		clearTimeout(this.timer);
		this.timer=null;
		location.hash='#home'
	},
	render:function(){
		var app=this.props.app,
			wallMode=this.props.wallMode,
			wallBackground=this.props.wallBackground,
			wallColor=this.props.wallColor,
			listArray=this.state.listArray,
			isPhone=this.props.isPhone,
			colNum=$('#main')&&!isPhone?parseInt($('#main').width()/250):1,
			hasLogo=this.props.hasLogo,
			Plan=typeof plan!='undefined'?plan:null,
			isHideLogo=(Plan && Plan.features) ? Plan.features.is_hide_parllay_logo : false;

		return (
			<div className="main giant_screen giant_gem_screen" ref="giant_gem_screen" onClick={this.close} style={{backgroundColor:wallBackground}}>
				<div ref='temp' style={{position:'fixed',right:10,top:10,zIndex:10000,fontSize:'20px'}}></div>
				<div id="main">
					{listArray.map(function(i,index){
						var position={
							l:index%colNum*250+10,
							t:parseInt(index/colNum)*250+10
						}
						return <MainListGemItem key={index} isPhone={isPhone} position={position} model={i} index={index} wallColor={wallColor} wallMode={wallMode} />
					})}
				</div>
				{hasLogo?<img className="parllay_logo" src={!isHideLogo?"/dashboard/images/sign-in-logo.png":wallLogo} />:''}
			</div>
		)
	}
});

/*多屏设置*/
var MixtureSetting = React.createClass({
	colorList:['#333333','#7f7f7f','#c3c3c3','#f3f3f3','#ffffff','#8b0018','#f3152b','#ff7d3b','#fff14f','#00b159','#00a3e3','#434bc5','#a74a9f','#bc795c','#ffaec8','#ffc844','#efe4b5','#b0e54f','#95d9e8','#6f93bb','#c9bfe4'],
	chooseMode:function(mode){
		this.props.wrapper.setState({
			mixtureMode:mode
		})
	},
	chooseBackground:function(color){
		this.props.wrapper.setState({
			mixtureBackground:color
		})
	},
	chooseTextColor:function(color){
		this.props.wrapper.setState({
			mixtureColor:color
		})
	},
	chooseSpeed:function(speed){
		this.props.wrapper.setState({
			mixtureSpeed:speed
		})
	},
	componentDidMount:function(){
		//$(this.refs.firstTab).focus()
	},
	render:function(){
		var self=this,
			title=this.props.title,
			colorList=this.colorList,
			mixtureMode=this.props.mixtureMode,
			mixtureBackground=this.props.mixtureBackground,
			mixtureColor=this.props.mixtureColor,
			mixtureSpeed=this.props.mixtureSpeed, //mixtureControllers
			speedList=this.props.speedList,
			modeSwatches=[];

		for(var i in mixtureControllers){
			(function(i){
				var mode=mixtureControllers[i];
				modeSwatches.push(<a key={i} href="javascript:void(0)" className={mixtureMode==i?"swatch swatch_selected mixture_screen "+mode.className:"swatch mixture_screen "+mode.className} onClick={function(){self.chooseMode(i)}}>{mode.screens.map(function(screen,index){
					return <div key={index}>{screen.name}</div>
				})}</a>)
			})(i)
		}

		return (
			<div className="weui_dialog_alert">
			    <div className="weui_mask"></div>
			    <div className="weui_dialog weui_dialog_confirm setting">
			        <div className="weui_dialog_hd weui_dialog_maintitle"><strong className="weui_dialog_title">{title}</strong></div>
			        <div className="weui_dialog_bd">
			        	<div className="swatches">
			        		{modeSwatches}
			        	</div>
			        </div>
			        <div className="weui_dialog_hd weui_dialog_subtitle"><strong className="weui_dialog_title">选择播放速度</strong></div>
			        <div className="weui_dialog_bd">
			        	<div className="swatches">
			        		{speedList.map(function(i,index){
			        			return (
			        				<a key={index} href="javascript:void(0)" className={mixtureSpeed==index?"swatch swatch_small swatch_selected":"swatch swatch_small"} onClick={function(){self.chooseSpeed(index)}}>{i.name}</a>
			        			)
			        		})}
			        	</div>
			        </div>
			        {mixtureMode!=1?<div className="weui_dialog_hd weui_dialog_subtitle"><strong className="weui_dialog_title">选择背景颜色</strong></div>:''}
			        {mixtureMode!=1?<div className="weui_dialog_bd">
			        	<div className="swatches">
			        		<div className="swatch swatch_small swatch_default" style={{backgroundColor:mixtureBackground}}></div>
			        		<span></span>
			        		{colorList.map(function(i,index){
			        			return (
			        				<a key={index} href="javascript:void(0)" className="swatch swatch_small" style={{backgroundColor:i}} onClick={function(){self.chooseBackground(i)}}></a>
			        			)
			        		})}
			        	</div>
			        </div>:''}
			        <div className="weui_dialog_hd weui_dialog_subtitle"><strong className="weui_dialog_title">选择文本颜色</strong></div>
			        <div className="weui_dialog_bd">
			        	<div className="swatches">
			        		<div className="swatch swatch_small swatch_default" style={{backgroundColor:mixtureColor}}></div>
			        		<span></span>
			        		{colorList.map(function(i,index){
			        			return (
			        				<a key={index} href="javascript:void(0)" className="swatch swatch_small" style={{backgroundColor:i}} onClick={function(){self.chooseTextColor(i)}}></a>
			        			)
			        		})}
			        	</div>
			        </div>
			        <div className="weui_dialog_ft">
			        	<a href="#home" className="weui_btn_dialog default">取消</a>
			            <a href="#mixture-player" className="weui_btn_dialog primary">播放</a>
			        </div>
			    </div>
			</div>
		)
	}
});

/*大屏设置*/
var SliderSetting = React.createClass({
	colorList:['#333333','#7f7f7f','#c3c3c3','#f3f3f3','#ffffff','#8b0018','#f3152b','#ff7d3b','#fff14f','#00b159','#00a3e3','#434bc5','#a74a9f','#bc795c','#ffaec8','#ffc844','#efe4b5','#b0e54f','#95d9e8','#6f93bb','#c9bfe4'],
	chooseMode:function(mode){
		this.props.wrapper.setState({
			sliderMode:mode
		})
	},
	chooseBackground:function(color){
		this.props.wrapper.setState({
			sliderBackground:color
		})
	},
	chooseTextColor:function(color){
		this.props.wrapper.setState({
			sliderColor:color
		})
	},
	chooseSpeed:function(speed){
		this.props.wrapper.setState({
			sliderSpeed:speed
		})
	},
	componentDidMount:function(){
		//$(this.refs.firstTab).focus()
	},
	render:function(){
		var self=this,
			title=this.props.title,
			colorList=this.colorList,
			sliderMode=this.props.sliderMode,
			sliderBackground=this.props.sliderBackground,
			sliderColor=this.props.sliderColor,
			sliderSpeed=this.props.sliderSpeed,
			sliderSpeedList=this.props.sliderSpeedList;

		return (
			<div className="weui_dialog_alert">
			    <div className="weui_mask"></div>
			    <div className="weui_dialog weui_dialog_confirm setting">
			        <div className="weui_dialog_hd weui_dialog_maintitle"><strong className="weui_dialog_title">{title}</strong></div>
			        <div className="weui_dialog_bd">
			        	<div className="swatches">
			        		<a href="javascript:void(0)" className={sliderMode==0?"swatch swatch_selected":"swatch"} onClick={function(){self.chooseMode(0)}} ref="firstTab">左右模式</a>
			        		<a href="javascript:void(0)" className={sliderMode==1?"swatch swatch_selected":"swatch"} onClick={function(){self.chooseMode(1)}}>大图模式</a>
			        		<a href="javascript:void(0)" className={sliderMode==2?"swatch swatch_selected":"swatch"} onClick={function(){self.chooseMode(2)}}>圆球模式</a>
			        	</div>
			        </div>
			        <div className="weui_dialog_hd weui_dialog_subtitle"><strong className="weui_dialog_title">选择播放速度</strong></div>
			        <div className="weui_dialog_bd">
			        	<div className="swatches">
			        		{sliderSpeedList.map(function(i,index){
			        			return (
			        				<a key={index} href="javascript:void(0)" className={sliderSpeed==index?"swatch swatch_small swatch_selected":"swatch swatch_small"} onClick={function(){self.chooseSpeed(index)}}>{i.name}</a>
			        			)
			        		})}
			        	</div>
			        </div>
			        {sliderMode!=1?<div className="weui_dialog_hd weui_dialog_subtitle"><strong className="weui_dialog_title">选择背景颜色</strong></div>:''}
			        {sliderMode!=1?<div className="weui_dialog_bd">
			        	<div className="swatches">
			        		<div className="swatch swatch_small swatch_default" style={{backgroundColor:sliderBackground}}></div>
			        		<span></span>
			        		{colorList.map(function(i,index){
			        			return (
			        				<a key={index} href="javascript:void(0)" className="swatch swatch_small" style={{backgroundColor:i}} onClick={function(){self.chooseBackground(i)}}></a>
			        			)
			        		})}
			        	</div>
			        </div>:''}
			        <div className="weui_dialog_hd weui_dialog_subtitle"><strong className="weui_dialog_title">选择文本颜色</strong></div>
			        <div className="weui_dialog_bd">
			        	<div className="swatches">
			        		<div className="swatch swatch_small swatch_default" style={{backgroundColor:sliderColor}}></div>
			        		<span></span>
			        		{colorList.map(function(i,index){
			        			return (
			        				<a key={index} href="javascript:void(0)" className="swatch swatch_small" style={{backgroundColor:i}} onClick={function(){self.chooseTextColor(i)}}></a>
			        			)
			        		})}
			        	</div>
			        </div>
			        <div className="weui_dialog_ft">
			        	<a href="#home" className="weui_btn_dialog default">取消</a>
			            <a href="#slider-player" className="weui_btn_dialog primary">播放</a>
			        </div>
			    </div>
			</div>
		)
	}
});

/*瀑布流设置*/
var WallSetting = React.createClass({
	colorList:['#333333','#7f7f7f','#c3c3c3','#f3f3f3','#ffffff','#8b0018','#f3152b','#ff7d3b','#fff14f','#00b159','#00a3e3','#434bc5','#a74a9f','#bc795c','#ffaec8','#ffc844','#efe4b5','#b0e54f','#95d9e8','#6f93bb','#c9bfe4'],
	chooseMode:function(mode){
		this.props.wrapper.setState({
			wallMode:mode
		})
	},
	chooseBackground:function(color){
		this.props.wrapper.setState({
			wallBackground:color
		});
		//$('#PCMenu').css('backgroundColor',color)
	},
	chooseTextColor:function(color){
		this.props.wrapper.setState({
			wallColor:color
		})
	},
	chooseSpeed:function(speed){
		this.props.wrapper.setState({
			wallSpeed:speed
		})
	},
	componentDidMount:function(){
		///$(this.refs.firstTab).focus()
	},
	render:function(){
		var self=this,
			title=this.props.title,
			colorList=this.colorList,
			wallMode=this.props.wallMode,
			wallBackground=this.props.wallBackground,
			wallColor=this.props.wallColor,
			wallSpeed=this.props.wallSpeed,
			wallSpeedList=this.props.wallSpeedList;

		return (
			<div className="weui_dialog_alert">
			    <div className="weui_mask"></div>
			    <div className="weui_dialog weui_dialog_confirm setting">
			        <div className="weui_dialog_hd weui_dialog_maintitle"><strong className="weui_dialog_title">{title}</strong></div>
			        <div className="weui_dialog_bd">
			        	<div className="swatches">
			        		<a className={wallMode==0?"swatch swatch_selected":"swatch"} href="javascript:void(0)" onClick={function(){self.chooseMode(0)}} ref="firstTab">图文模式</a>
			        		<a className={wallMode==1?"swatch swatch_selected":"swatch"} href="javascript:void(0)" onClick={function(){self.chooseMode(1)}}>图片模式</a>
			        		<a className={wallMode==4?"swatch swatch_selected":"swatch"} href="javascript:void(0)" onClick={function(){self.chooseMode(4)}}>网格模式</a>
			        		<a className={wallMode==2?"swatch swatch_selected":"swatch"} href="javascript:void(0)" onClick={function(){self.chooseMode(2)}}>珍珠模式</a>
			        		<a className={wallMode==3?"swatch swatch_selected":"swatch"} href="javascript:void(0)" onClick={function(){self.chooseMode(3)}}>宝石模式</a>
			        	</div>
			        </div>
			        <div className="weui_dialog_hd weui_dialog_subtitle"><strong className="weui_dialog_title">选择播放速度</strong></div>
			        <div className="weui_dialog_bd">
			        	<div className="swatches">
			        		{wallSpeedList.map(function(i,index){
			        			return (
			        				<a key={index} href="javascript:void(0)" className={wallSpeed==index?"swatch swatch_small swatch_selected":"swatch swatch_small"} onClick={function(){self.chooseSpeed(index)}}>{i.name}</a>
			        			)
			        		})}
			        	</div>
			        </div>
			        <div className="weui_dialog_hd weui_dialog_subtitle"><strong className="weui_dialog_title">选择背景颜色</strong></div>
			        <div className="weui_dialog_bd">
			        	<div className="swatches">
			        		<div className="swatch swatch_small swatch_default" style={{backgroundColor:wallBackground}}></div>
			        		<span></span>
			        		{colorList.map(function(i,index){
			        			return (
			        				<a key={index} href="javascript:void(0)" className="swatch swatch_small" style={{backgroundColor:i}} onClick={function(){self.chooseBackground(i)}}></a>
			        			)
			        		})}
			        	</div>
			        </div>
			        <div className="weui_dialog_hd weui_dialog_subtitle"><strong className="weui_dialog_title">选择文本颜色</strong></div>
			        <div className="weui_dialog_bd">
			        	<div className="swatches">
			        		<div className="swatch swatch_small swatch_default" style={{backgroundColor:wallColor}}></div>
			        		<span></span>
			        		{colorList.map(function(i,index){
			        			return (
			        				<a key={index} href="javascript:void(0)" className="swatch swatch_small" style={{backgroundColor:i}} onClick={function(){self.chooseTextColor(i)}}></a>
			        			)
			        		})}
			        	</div>
			        </div>
			        <div className="weui_dialog_ft">
			        	<a href="#home" className="weui_btn_dialog default">取消</a>
			            <a href="#wall-player" className="weui_btn_dialog primary">播放</a>
			        </div>
			    </div>
			</div>
		)
	}
});

/*工具组件*/
/*上拉菜单*/
var ActionSheet = React.createClass({
	shouldComponentUpdate:function(nextProps, nextState){
		return this.props.actionSheet!=nextProps.actionSheet
	},
	close:function(){
		this.props.app.react.setState({
			actionSheet:false
		})
	},
	render:function(){
		var isOpen=this.props.actionSheet,
			list=isOpen?isOpen.list:[];

		return (
			<div id="actionSheet_wrap" style={{position:'relative',zIndex:1031}}>
			    <div className={isOpen?"weui_mask_transition weui_fade_toggle":"weui_mask_transition"} style={isOpen?{display:'block'}:{display:'none'}} id="mask"></div>
			    <div className={isOpen?"weui_actionsheet weui_actionsheet_toggle":"weui_actionsheet"} id="weui_actionsheet">
			        {list.map(function(i){
			        	return <div className="weui_actionsheet_menu">
				            {i.href?<a href={i.href} style={{display:'block'}} className="weui_actionsheet_cell">{i.name}</a>:<div onClick={i.callback} className="weui_actionsheet_cell">{i.name}</div>}
				        </div>
			        })}
			        <div className="weui_actionsheet_action">
			            <div className="weui_actionsheet_cell" id="actionsheet_cancel" onClick={this.close}>取消</div>
			        </div>
			    </div>
			</div>
		)
	}
});

/*加载动画*/
var Loading = React.createClass({
	render:function(){
		return (
			<div className="weui_loading_toast">
			    <div className="weui_mask_transparent"></div>
			    <div className="weui_toast">
			        <div className="weui_loading">
			            <div className="weui_loading_leaf weui_loading_leaf_0"></div>
			            <div className="weui_loading_leaf weui_loading_leaf_1"></div>
			            <div className="weui_loading_leaf weui_loading_leaf_2"></div>
			            <div className="weui_loading_leaf weui_loading_leaf_3"></div>
			            <div className="weui_loading_leaf weui_loading_leaf_4"></div>
			            <div className="weui_loading_leaf weui_loading_leaf_5"></div>
			            <div className="weui_loading_leaf weui_loading_leaf_6"></div>
			            <div className="weui_loading_leaf weui_loading_leaf_7"></div>
			            <div className="weui_loading_leaf weui_loading_leaf_8"></div>
			            <div className="weui_loading_leaf weui_loading_leaf_9"></div>
			            <div className="weui_loading_leaf weui_loading_leaf_10"></div>
			            <div className="weui_loading_leaf weui_loading_leaf_11"></div>
			        </div>
			        <p className="weui_toast_content">数据加载中</p>
			    </div>
			</div>
		)
	}
});

/*确认对话框*/
var ConfirmDialog = React.createClass({
	shouldComponentUpdate:function(nextProps, nextState){
		return JSON.stringify(this.props.options)!=JSON.stringify(nextProps.options)
	},
	close:function(){
		var app=this.props.app,
			options=this.props.options;

		app.react.setState({
			confirmOptions:null
		});
		return options
	},
	cancel:function(){
		var options=this.close();

		if(options.cancel){
			options.cancel()
		}
	},
	confirm:function(){
		var options=this.close();

		if(options.confirm){
			options.confirm()
		}
	},
	render:function(){
		var options=this.props.options;

		return (
			<div>
				{options?<div>
				    <div className="weui_mask"></div>
				    <div className="weui_dialog">
				        <div className="weui_dialog_hd"><strong className="weui_dialog_title">{options.title || '确认对话框'}</strong></div>
				        <div className="weui_dialog_bd">{options.content}</div>
				        <div className="weui_dialog_ft">
				            <a href="javascript:void(0);" className="weui_btn_dialog default" onClick={this.cancel}>取消</a>
				            <a href="javascript:void(0);" className="weui_btn_dialog primary" onClick={this.confirm}>确定</a>
				        </div>
				    </div>
				</div>:''}
			</div>
		)
	}
});

/*app主体*/
var Wrapper = React.createClass({
	getInitialState:function(){
		return {
			index:0,
			router:'mainList',
			mainCollection:this.props.app.mainCollection,
			pendingCollection:this.props.app.pendingCollection,
			approvedCollection:this.props.app.approvedCollection,
			rejectedCollection:this.props.app.rejectedCollection,
			deletedCollection:this.props.app.deletedCollection,
			hotCollection:this.props.app.hotCollection,
			setting:false,
			mixtureMode:'left1-right2',
			mixtureBackground:'transparent',
			mixtureColor:'#333333',
			mixtureSpeed:1,
			sliderMode:0,
			sliderBackground:'transparent',
			sliderColor:'#333333',
			sliderSpeed:1,
			wallMode:0,
			wallBackground:'transparent',
			wallColor:'#333333',
			wallSpeed:1,
			logo:wallLogo,
			mainTitle:wallName,
			describe:wallDescription,
			qrCode:wallQrcode,
			message:null,
			actionSheet:false,
			userPhotoCollection:[],
			userInfo:{},
			isPhone:this.props.isPhone,
			confirmOptions:null,
			isLoading:false,
			status:'pending'
		}
	},
	/*shouldComponentUpdate:function(nextProps, nextState){
		for(var i in this.state){
			if(JSON.stringify(nextState[i])!=JSON.stringify(this.state[i])){
				return true
			}
		}
		return false
	},*/
	sliderSpeedList:[
		{name:'快',val:3333},
		{name:'中',val:6666},
		{name:'慢',val:10000}
	],
	wallSpeedList:[
		{name:'快',val:2},
		{name:'中',val:1},
		{name:'慢',val:0.5}
	],
	render:function(){
		var app=this.props.app,
			setting=this.state.setting,
			mixtureMode=this.state.mixtureMode,
			mixtureBackground=this.state.mixtureBackground,
			mixtureColor=this.state.mixtureColor,
			mixtureSpeed=this.state.mixtureSpeed,
			sliderMode=this.state.sliderMode,
			sliderBackground=this.state.sliderBackground,
			sliderColor=this.state.sliderColor,
			sliderSpeed=this.state.sliderSpeed,
			sliderSpeedList=this.sliderSpeedList,
			wallMode=this.state.wallMode,
			wallBackground=this.state.wallBackground,
			wallColor=this.state.wallColor,
			wallSpeed=this.state.wallSpeed,
			wallSpeedList=this.wallSpeedList,
			isLoading=this.state.isLoading,
			isPhone=this.state.isPhone,
			settingHtml='';

		if(setting){
			var settingTitle=app.menuRouters[setting].title;

			switch(setting){
				case 'mixtureSetting':
					settingHtml=<MixtureSetting title={settingTitle} wrapper={this} mixtureMode={mixtureMode} mixtureBackground={mixtureBackground} mixtureColor={mixtureColor} mixtureSpeed={mixtureSpeed} speedList={sliderSpeedList} />
					break;
				case 'sliderSetting':
					settingHtml=<SliderSetting title={settingTitle} wrapper={this} sliderMode={sliderMode} sliderBackground={sliderBackground} sliderColor={sliderColor} sliderSpeed={sliderSpeed} sliderSpeedList={sliderSpeedList} />
					break;
				case 'wallSetting':
					settingHtml=<WallSetting title={settingTitle} wrapper={this} wallMode={wallMode} wallBackground={wallBackground} wallColor={wallColor} wallSpeed={wallSpeed} wallSpeedList={wallSpeedList} />
					break;
			}
		}

		return (
			<div className="wrapper">
				<ListTemplate wrapper={this}  />
				{settingHtml}
				{isLoading?<Loading />:''}
				{!isPhone?<LoadItemsWithoutSize collection={this.state.mainCollection} />:''}
			</div>
		)
	}
});

/*****************backbone 路由******************/

var AppRouter = Backbone.Router.extend({
	initialize:function () {
		//location.hash='';

		moment.locale('en', {
		    relativeTime : {
		        past:   "%s前",
		        m:  "1分钟",
		        mm: "%d分钟",
		        h:  "1小时",
		        hh: "%d小时",
		        d:  "1天",
		        dd: "%d天",
		        M:  "1月",
		        MM: "%d月",
		        y:  "1年",
		        yy: "%d年"
		    }
		});

		/*collection1*/
		this.mainCollection=new CollectionList();
		this.mainCollection.comparator=this.descSort;
		this.mainCollection.on('all',function(type,item,list){
			this.react.setState({
				mainCollection:this.mainCollection
			})
		},this);

		/*collection2*/
		this.pendingCollection=new CollectionList();
		this.pendingCollection.comparator=this.descSort;
		this.pendingCollection.on('all',function(item,list){
			this.react.setState({
				pendingCollection:this.pendingCollection
			})
		},this);
		/*collection2.2*/
		this.approvedCollection=new CollectionList();
		this.approvedCollection.comparator=this.descSort;
		this.approvedCollection.on('all',function(item,list){
			this.react.setState({
				approvedCollection:this.approvedCollection
			})
		},this);
		/*collection2.3*/
		this.rejectedCollection=new CollectionList();
		this.rejectedCollection.comparator=this.descSort;
		this.rejectedCollection.on('all',function(item,list){
			this.react.setState({
				rejectedCollection:this.rejectedCollection
			})
		},this);
		/*collection2.4*/
		this.deletedCollection=new CollectionList();
		this.deletedCollection.comparator=this.descSort;
		this.deletedCollection.on('all',function(item,list){
			this.react.setState({
				deletedCollection:this.deletedCollection
			})
		},this);

		/*collection3*/
		this.hotCollection=new CollectionList();
		//this.hotCollection.comparator=this.descSort;
		this.hotCollection.on('all',function(item,list){
			this.react.setState({
				hotCollection:this.hotCollection
			})
		},this);

		/*config*/
		this.openId=true;
		this.isAnoymous=isAnoymous;
		this.isAdmin=isAdmin;

		this.react=ReactDOM.render(<Wrapper app={this} isPhone={($(window).width()<768 && !isTV())} />,document.getElementById('wrapper'));

		this.bindTouchEvent();

		/*timer*/
		this.setRealtimePermission()

	},
	setRealtimePermission:function(){
		var self=this,
			Plan=typeof plan!='undefined'?plan:null,
			timer=is_realtime ? 30000 : ((Plan && Plan.features) ? Plan.features.screen_update_interval*1000 : 600000);

		setTimeout(function(){
			self.loadNew(null,function(data){
				if(is_realtime && ((new Date()).getTime()<realtime_stop_timestamp)){
					var data=data?_.filter(data.data,function(i){ return i.type!='video'}):[];
					if(location.hash.indexOf('player')>=0  && data && data.length){
						ReactDOM.render(<PokerList data={data} callback={function(){
							ReactDOM.unmountComponentAtNode(document.getElementById('realtime'));
							self.setRealtimePermission()
						}} />,document.getElementById('realtime'))
					}else{
						self.setRealtimePermission()
					}
				}else{
					is_realtime=false;
					self.setRealtimePermission()
				}
			})
		},timer)
	},
	validateOpenId:function(){
		if(!this.openId){
			this.navigate('error',{trigger: true});
			return false
		}
		return true
	},
	routes:{
		'home':'mainList',
		'home-hot':'mainListHot',
		'photo':'uploadPhoto',
		'auditing/:id':'adminAuditing',
		'setting':'userSetting',
		'setname':'userSetname',
		'mixture-player':'mixturePlayer',
		'slider-player':'sliderPlayer',
		'wall-player':'wallPlayer',
		'mixture-setting':'mixtureSetting',
		'slider-setting':'sliderSetting',
		'wall-setting':'wallSetting',
		'error':'error',
		'*acts':'mainList'
	},
	menuRouters:{
		'mainList':{
			title:'图片墙',
			index:0
		},
		'mainListHot':{
			title:'图片墙',
			index:0
		},
		'uploadPhoto':{
			title:'传图片',
			index:1
		},
		'adminAuditing':{
			title:'管理员审核',
			index:2
		},
		'userSetting':{
			title:'管理员设置',
			index:3
		},
		'userSetname':{
			title:'设置昵称',
			index:3
		},
		'mixturePlayer':{
			title:'分屏播放',
			index:-1
		},
		'sliderPlayer':{
			title:'大图播放',
			index:-1
		},
		'wallPlayer':{
			title:'多图播放',
			index:-1
		},
		'mixtureSetting':{
			title:'多屏模式',
			index:0
		},
		'sliderSetting':{
			title:'大屏模式',
			index:0
		},
		'wallSetting':{
			title:'瀑布流模式',
			index:0
		},
		'error':{
			title:'错误',
			index:-1
		}
	},
	mainList:function() {
		this.currentList='mainCollection';

		/*this.react.setState({
			router:'mainList'
		});*/

		if(!this.mainLoaded){
			this.mainListPage=0;
			this.loadMore();
			this.mainLoaded=true
		}else{
			this.loadNew('mainCollection')
		}
		this.clean()
	},
	mainListHot:function(){
		this.currentList='hotCollection';

		/*this.react.setState({
			router:'mainListHot'
		});*/

		if(!this.list3Loaded){
			this.mainListHot=0;
			this.loadMore();
			this.list3Loaded=true
		}else{
			this.loadMore()
		}
		this.clean(true)
	},
	uploadPhoto:function(){
		this.currentList='others';
		/*this.react.setState({
			router:'uploadPhoto'
		});*/
		this.clean()
	},
	adminAuditing:function(status){
		status=status=='approved'?'main':status;

		var collectionName=status+'Collection',
			isLoadBoo=status+'Loaded',
			pageCount=status+'ListPage';

		this.currentList=collectionName;

		/*this.react.setState({
			router:'adminAuditing'
		});*/

		if(!this[isLoadBoo]){
			this[pageCount]=0;
			this.loadMore();
			this[isLoadBoo]=true
		}else{
			this.loadNew(collectionName)
		}
		this.clean()
	},
	userSetting:function(){
		this.currentList='others';
		/*this.react.setState({
			router:'userSetting'
		});*/
		this.clean()
	},
	userSetname:function(){
		this.currentList='others';
		/*this.react.setState({
			router:'userSetname'
		});*/
		this.clean()
	},
	mixturePlayer:function(){
		var self=this;
		this.currentList='mainCollection';

		(function loadMore(){
			if(!self.mainCollection.complete){
				self.loadMore('mainCollection',loadMore)
			}
		})()

		/*this.react.setState({
			router:'mixturePlayer'
		});*/

		this.clean(true)
	},
	sliderPlayer:function(){
		var self=this;
		this.currentList='mainCollection';

		(function loadMore(){
			if(!self.mainCollection.complete){
				self.loadMore('mainCollection',loadMore)
			}
		})()

		/*this.react.setState({
			router:'sliderPlayer'
		});*/

		this.clean(true)
	},
	wallPlayer:function(){
		var self=this;
		this.currentList='mainCollection';

		(function loadMore(){
			if(!self.mainCollection.complete){
				self.loadMore('mainCollection',loadMore)
			}
		})()

		/*this.react.setState({
			router:'wallPlayer'
		});*/

		this.clean(true)
	},
	mixtureSetting:function(){
		this.currentList='others';
		this.react.setState({
			setting:'mixtureSetting'
		});
		$('body').css('overflow','hidden')
	},
	sliderSetting:function(){
		this.currentList='others';
		this.react.setState({
			setting:'sliderSetting'
		});
		$('body').css('overflow','hidden')
	},
	wallSetting:function(){
		this.currentList='others';
		this.react.setState({
			setting:'wallSetting'
		});
		$('body').css('overflow','hidden')
	},
	error:function(){
		this.currentList='others';
		ReactDOM.unmountComponentAtNode(document.getElementById('menu'))(document.getElementById('menu'));
		this.menu=null;
		this.clean();
		var isError=$('#errorInfo').val();
		if(isError){
			alert(isError)
		}else{
			var url=encodeURIComponent('http://now-ppe.parllay.cn/router/index?url='+encodeURIComponent('http://'+window.location.host+window.location.pathname));
			window.location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxfd8db2900c3f9877&redirect_uri='+url+'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect'
		}
	},
	clean:function (special) {
		document.documentElement.scrollTop = document.body.scrollTop =0;
		
		if(this.currentList!='others' && !special){
			if(!this[this.currentList].complete){
				if(window.specialScrollBinder){
					this.scrollContainer=specialScrollBinder(this.loadMore.bind(this))
				}else{
					this.scrollContainer=$(window).unbind('scroll').bind('scroll',function(){
						var scrollTop = $(window).scrollTop();
						var scrollHeight = $(document).height();
						var windowHeight = $(window).height();
						if(scrollTop + windowHeight>=scrollHeight-50){
							this.loadMore()
						}
					}.bind(this))
				}
			}else{
				if(this.scrollContainer){
					this.scrollContainer.unbind('scroll')
				}
			}
		}else{
			if(this.scrollContainer){
				this.scrollContainer.unbind('scroll')
			}
		}

		this.react.setState({
			setting:false
		});
		$('body').css('overflow','auto')
	},
	bindTouchEvent:function(){
		try{
			document.addEventListener('touchstart',this.touchStart.bind(this),false);
			document.addEventListener('touchmove',this.touchMove.bind(this),false);
			document.addEventListener('touchend',this.touchEnd.bind(this),false)
		}
		catch(e){

		}
	},
	yStart:0,
	yEnd:0,
	touchStart:function(e){
		if(this.currentList!='others'){
			try{
				var touch = e.touches[0];
				this.yStart=touch.pageY
			}
			catch(e){

			}
		}
	},
	touchMove:function(e){
		if(this.currentList!='others'){
			try{
				var touch = e.touches[0],
					offsetY=touch.pageY-this.yStart,
					offsetTop=$(window).scrollTop();
				
				/*if(offsetY>=0){
					this.react.setState({
						message:'松开加载更多'
					})
				}*/

				this.yEnd=touch.pageY
			}
			catch(e){

			}
		}
	},
	touchEnd:function(e){
		if(this.currentList!='others'){
			try{
				var offsetY=this.yEnd-this.yStart,
					offsetTop=$(window).scrollTop();
					console.log(offsetY);
				if(offsetY>=50 && offsetTop==0){
					this.loadNew()
				}else{
					this.react.setState({
						message:null
					})
				}

			}
			catch(e){
				console.log(e)
			}
		}
	},
	loadNew:function(special,callback){
		var self=this;
		//this.isLoading=true;
		//$('#loadingToast').show();
		console.log(this.currentList);
		switch(special || this.currentList){
			case 'mainCollection':
				loadMore(this.mainCollection,'/wall/');
				break;
			case 'pendingCollection':
				loadMore(this.pendingCollection,'/wall/','pending');
				break;
			case 'approvedCollection':
				loadMore(this.approvedCollection,'/wall/','approved&platform=console');
				break;
			case 'rejectedCollection':
				loadMore(this.rejectedCollection,'/wall/','rejected&platform=console');
				break;
			case 'deletedCollection':
				loadMore(this.deletedCollection,'/wall/','deleted&platform=console');
				break;
			case 'hotCollection':
				loadMore(this.hotCollection,'/wall/','hot');
				break;
		}

		this.react.setState({
			message:'加载中...'
		});

		function loadMore(collection,url,status){
			var first= collection.length ? collection.at(0).get('timestamp') : Date.now();
			$.ajax({
				url:url+wallId+'/photos?count=20&type=new&since='+first+(status?'&status='+status:''),
				dataType:'json',
				success:function(data){
					if(data){
						if(data.success){
							if(data.data.length){
								collection.add(data.data,{merge: true})
							}
						}
					}
					if(callback){callback(data)}
					self.react.setState({
						message:null
					})
				},
				error:function(){
					if(callback){callback()}
					self.showLoading(false);
					$('#toast').show();
					setTimeout(function(){$('#toast').hide()},3000)
					self.react.setState({
						message:null
					})
				}
			});
			//self.isLoading=false;
		}
	},
	loadMore:function(special,callback){
		var self=this;
		if(this[special || this.currentList].complete){
			return
		}
		
		switch(special || this.currentList){
			case 'mainCollection':
				if(!this.mainLoading){
					this.mainLoading=true;
					loadMore(this.mainCollection,'/wall/','mainLoading')
				}
				break;
			case 'pendingCollection':
				if(!this.pendingLoading){
					this.pendingLoading=true;
					loadMore(this.pendingCollection,'/wall/','pendingLoading','pending')
				}
				break;
			case 'approvedCollection':
				if(!this.approvedLoading){
					this.approvedLoading=true;
					loadMore(this.approvedCollection,'/wall/','approvedLoading','approved&platform=console')
				}
				break;
			case 'rejectedCollection':
				if(!this.rejectedLoading){
					this.rejectedLoading=true;
					loadMore(this.rejectedCollection,'/wall/','rejectedLoading','rejected&platform=console')
				}
				break;
			case 'deletedCollection':
				if(!this.deletedLoading){
					this.deletedLoading=true;
					loadMore(this.deletedCollection,'/wall/','deletedLoading','deleted&platform=console')
				}
				break;
			case 'hotCollection':
				if(!this.hotLoading){
					this.hotLoading=true;
					loadMore(this.hotCollection,'/wall/','hotLoading',null,'hot')
				}
				break;
		}
		function loadMore(collection,url,loading,status,mode){

			if(!special){self.showLoading(true)}

			setTimeout(function(){
				/*if(!url.slice(8*(page+1),8*(page+2)).length){
					collection.complete=true
				}
				collection.add(url.slice(8*page,8*(page+1)));*/
				var isHot=mode=='hot',
					last= (collection.length && !isHot) ? collection.at(collection.length-1).get('timestamp') : Date.now();
				$.ajax({
					url:url+wallId+'/photos?count=20&type=old&since='+last+(status?'&status='+status:'')+(mode?'&mode='+mode:''),
					dataType:'json',
					success:function(data){
						try{
							if(data){
								if(data.success){
									if(isHot){
										collection.reset(data.data)
									}else{
										if(data.data.length){
											collection.add(data.data,{merge: true});
											setTimeout(function(){
												if(callback){callback(data.data)}
											})
										}else{
											if(callback){callback()}
											//collection.add(taskListModel);
											if(!last && !status && !self.isAnoymous && canUpload){
												location.hash='photo'
											}
											collection.complete=true
										}
									}

									if(!special){self.showLoading(false)}
								}else{
									if(callback){callback()}
								}
							}else{
								if(callback){callback()}
							}
						}catch(e){
							if(callback){callback()}
							console.log(e.stack)
						}
					},
					error:function(){
						if(callback){callback()}
						self.showLoading(false);
						$('#toast').show();
						setTimeout(function(){$('#toast').hide()},3000)
					}
				});
				self[loading]=false;
			},1000)
		}
	},
	showLoading:function(boo){
		this.react.setState({
			isLoading:!!boo
		})
	},
	removeModel:function(c,id){
		var m=this[c].get(id);
		if(m){
			return this[c].remove(m)
		}
		return null
	},
	addMedel:function(c,m){
		this[c].add(m,{merge: true})
	},
	getNewTimestamp:function(c,m){
		var collection=this[c],
			first=collection.length?collection.at(0).get('timestamp'):Date.now(),
			last=collection.length?collection.at(collection.length-1).get('timestamp'):Date.now(),
			modelTimestamp=m.get('timestamp');

		if(modelTimestamp<last){
			return (last-1)
		}
		else if(modelTimestamp>first){
			return (first+1)
		}

		return modelTimestamp
	},
	descSort:function(m1,m2){
		return m2.get('timestamp')-m1.get('timestamp')
	}
});



$(function(){
	var app = new AppRouter;
	app.on('route',function(router,param){
		var index=this.menuRouters[router].index;

		if(this.menu){
			this.menu.setState({
				router:index
			})
		}
		if(this.react){
			var reactState={
				router:router
			};

			if(param[0]){
				reactState.status=param[0]
			}

			this.react.setState(reactState)
		}
		//document.title=this.menuRouters[e].title
	});
	Backbone.history.start({
		beforeAction:function(){
			$('#loadingToast').hide()
		}
	});
	app.validateOpenId()
});

//alert(navigator.userAgent)
function isTV() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ['Parllay']; //"Android", "iPhone","SymbianOS", "Windows Phone","iPad", "iPod"
    var flag = false;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) >= 0) {
            flag = true;
            break;
        }
    }
    return flag;
}

/*扑克牌动画*/
var PokerList = React.createClass({
	getInitialState:function(){
		var data=this.props.data;

		this.initialize();

		this.currentAnimationItem=data.length>1?-1:0

		return {
			data:data
		}
	},
	pokerPadding:70,
	loaded:0,
	isAnimating:false,
	timer:null,
	shouldComponentUpdate:function(nextProps, nextState){
		return !this.isPokerMounted && !nextProps
	},
	componentDidMount:function(){

	},
	componentDidUpdate:function(){
		if(this.isPokerMounted){
			if(this.currentAnimationItem<=this.getItemLength()){
				this.animateStart()
			}else{
				this.animateStop()
			}
		}
	},
	componentWillUnmount:function(){
		//document.getElementById('wrapper').style.overflow=null
	},
	initialize:function(){
		//document.getElementById('wrapper').style.overflow='hidden'
	},
	onLoaded:function(e){
		var	datalength=this.getItemLength();

		this.setItemRatio(e);

		if(++this.loaded == datalength){
			this.isPokerMounted=true;
			this.forceUpdate()
		}
	},
	setItemRatio:function(e){
		var self=this,
			data=this.state.data,
			data=_.map(data,function(i){
				if(!i.ratio && (e.target.src.indexOf(i.isVideo?i.poster:i.photo_url)>=0)){
					i.ratio=(e.target.offsetHeight/e.target.offsetWidth).toFixed(2)
				}
				i.rotate=self.getItemRotation();
				i.zIndex=self.getItemZindex();

				return i
			});

		this.setState({
			data:data
		})
	},
	getItemLength:function(){
		var data=this.state.data;

		return data.length
	},
	getExpectItemWidth:function(isFill){
		var container=this.refs.container,
			padding=this.pokerPadding,
			width=container.offsetWidth-padding*2,
			height=container.offsetHeight-padding*2,
			pixel=width*height,
			datalength=this.getItemLength(),
			widthPerItem=_.min([Math.sqrt(pixel/datalength),350]);

		if(isFill){
			var colLength=Math.floor(width/widthPerItem),
				gap=(width-colLength*widthPerItem)/colLength;

			return {
				itemWidth:(widthPerItem+gap),
				colLength:colLength
			}
		}

		return widthPerItem
	},
	getItemZindex :function(){ 
		return Math.floor((Math.random()*5) + 1)
	},
    getItemRotation:function(){
    	var thumbRotation=45,
        	min = -1 * thumbRotation,
        	max = thumbRotation,
        	randomRotation = 'rotate(' + (Math.floor( Math.random() * (max - min + 1)) + min)+ 'deg)';

        return randomRotation
    },
	getItems:function(){
		var self=this,
			data=this.state.data;

		if(this.isPokerMounted){
			var positions=this.waterFallLayout(),
				container=this.refs.container,
				padding=this.pokerPadding,
				width=container.offsetWidth-padding*2,
				height=container.offsetHeight-padding*2,
				windowRatio=(height/width).toFixed(2);

			return data.map(function(i,index){
				var rotate=i.rotate,
					ratio=i.ratio,
					isThin=ratio>windowRatio,
					style=_.extend(positions[index],{
						position:'absolute',
						transform:rotate,
						MozTransform:rotate,
						WebkitTransform:rotate,
						OTransform:rotate,
						MsTransform:rotate,
						transitionDuration:'0.5s',
						MozTransitionDuration:'0.5s',
						WebkitTransitionDuration:'0.5s',
						OTransitionDuration:'0.5s',
						MsTransitionDuration:'0.5s',
						zIndex:i.zIndex,
						opacity:1
					});

				if((self.isAnimating && self.currentAnimationItem==index) || self.getItemLength()==1){
					style=_.extend(style,{
						width:isThin?height/ratio:width,
						height:isThin?height:width*ratio,
						left:isThin?'50%':0,
						top:isThin?0:'50%',
						transform:null,
						MozTransform:null,
						WebkitTransform:null,
						OTransform:null,
						MsTransform:null,
						zIndex:10000,
						marginLeft:isThin?-(height/ratio)/2:null,
						marginTop:isThin?null:-(width*ratio)/2
					})
				}

				if(self.currentAnimationItem>=self.getItemLength()){
					style=_.extend(style,{
						left:0,
						top:0,
						opacity:0
					})
				}

				return <PokerItem key={index} data={i} style={style} />
			})
		}else{
			return data.map(function(i,index){
				var rotate=self.getItemRotation();

				var style={
					position:'absolute',
					left:0,
					top:0,
					opacity:0
				};

				return <PokerItem key={index} data={i} style={style} onLoad={self.onLoaded} />
			})
		}
	},
	waterFallLayout:function(){
		var self=this,
			data=this.state.data,
			expectItem=this.getExpectItemWidth(true),
			itemWidth=expectItem.itemWidth,
			colLength=expectItem.colLength,
			tempArr=[],
			resultArr=[];

		data.forEach(function(i,index){
			var position=null;

			var col=tempArr.length!=colLength?index:_.indexOf(tempArr,_.min(tempArr)),
				t=tempArr[col] || -25;

			position={
				width:itemWidth,
				height:itemWidth*i.ratio,
				left:col*itemWidth,
				top:t
			}
			tempArr[col]=t+i.ratio*itemWidth-25;

			resultArr.push(position)
		});

		return resultArr
	},
	animateStart:function(){
		var self=this;
		
		this.isAnimating=true;

		this.clearTimer();

		this.timer=setTimeout(function(){
			self.currentAnimationItem++;
			self.forceUpdate()
		},this.currentAnimationItem>=this.getItemLength()?1000:3000)
	},
	animateStop:function(){
		var callback=this.props.callback;

		this.clearTimer();

		if(callback){
			setTimeout(callback,0)
		}
	},
	clearTimer:function(){
		if(this.timer){
			clearTimeout(this.timer);
			this.timer=null
		}
	},
	render:function(){

		return (
			<div className="poker-wrapper" ref="container" style={{padding:this.pokerPadding}}>
				<div className="poker-overlay"></div>
				<div className="poker-list">
					{this.getItems()}
				</div>
			</div>
		)
	}
});

var PokerItem = React.createClass({
	render:function(){
		var data=this.props.data,
			style=this.props.style,
			onLoad=this.props.onLoad,
			isFocus=style.zIndex==10000;

		return (
			<div className={isFocus?"poker-item poker-item-focus":"poker-item"} style={style}>
				<img src={data.isVideo?data.poster:data.photo_url} onLoad={onLoad} />
				<p>
					<img src={data.user.profile_image || '/images/default.png'} />
					{data.description}
				</p>
			</div>
		)
	}
});

/*瀑布流计算卡片位置*/
//function WaterFaller(){
	/*var app=this.props.app,
		isAuditing=this.props.isAuditing,
		wallMode=isAuditing?0:this.props.wallMode,
		wallBackground=this.props.wallBackground,
		wallColor=this.props.wallColor,
		collection=this.props.collection,
		listArray=this.state.listArray,
		len=listArray.length,
		isPhone=this.props.isPhone,
		colNum=!isPhone?Math.floor($(this.refs.giant_screen).width()/250):1,
		listHtml=[],
		tempArr=_.clone(this.placeholder),
		mainTop=this.state.mainTop,
		transform='translate(0px,'+mainTop+'px)',
		tranStyle=this.state.tranStyle,
		hasLogo=this.props.hasLogo;
		
		listArray.forEach(function(i,index){
			var model=i,
				position=null;

			if(colNum>1&&model.h){
				var col=tempArr.length!=colNum?index:_.indexOf(tempArr,_.min(tempArr)),
					t=tempArr[col] || 0;
				position={
					l:col*250,
					t:t
				}
				tempArr[col]=t+(wallMode?model.ratio*250:model.h)
			}
			switch (wallMode){
				case 0:
					listHtml.push(<MainListItem isAnimating={true} key={index} isPhone={isPhone} position={position} app={app} model={model} backboneModel={collection.get(model.id)} index={index} wallColor={wallColor} isAuditing={isAuditing} />);
					break;
				case 1:
					listHtml.push(<MainListPicItem key={index} isPhone={isPhone} position={position} model={model} backboneModel={collection.get(model.id)} index={index} wallColor={wallColor} />);
					break;
			}
		});

		this.tempArr=tempArr;*/

//};








